Skip to content

Instantly share code, notes, and snippets.

@nsdevaraj
Last active March 18, 2025 11:30
Show Gist options
  • Save nsdevaraj/d35a91a05556afe66cc80aed66db9045 to your computer and use it in GitHub Desktop.
Save nsdevaraj/d35a91a05556afe66cc80aed66db9045 to your computer and use it in GitHub Desktop.
"""
Business Simulation Decision Types
=================================
This module defines the various decision types available in the business simulation
and their specific parameters and effects.
"""
from typing import Dict, Any, List, Optional
from enum import Enum
class DecisionType(Enum):
"""Enumeration of available decision types in the simulation."""
PRODUCT_DEVELOPMENT = "product_development"
PRICING = "pricing"
MARKETING = "marketing"
RESOURCE_ALLOCATION = "resource_allocation"
INVESTMENT = "investment"
PRODUCTION = "production"
HUMAN_RESOURCES = "human_resources"
RESEARCH_DEVELOPMENT = "research_development"
SUPPLY_CHAIN = "supply_chain"
EXPANSION = "expansion"
class DecisionSchema:
"""Defines schemas for different decision types."""
@staticmethod
def get_schema(decision_type: DecisionType) -> Dict[str, Any]:
"""
Get the schema for a specific decision type.
Args:
decision_type: The type of decision
Returns:
Dict containing the schema definition
"""
schemas = {
DecisionType.PRODUCT_DEVELOPMENT: {
"type": "object",
"required": ["product_data"],
"properties": {
"product_data": {
"type": "object",
"required": ["name", "category", "quality_level"],
"properties": {
"id": {"type": "string"},
"name": {"type": "string"},
"category": {"type": "string"},
"quality_level": {"type": "number", "minimum": 1, "maximum": 10},
"innovation_level": {"type": "number", "minimum": 1, "maximum": 10},
"development_cost": {"type": "number", "minimum": 0},
"production_cost": {"type": "number", "minimum": 0},
"selling_price": {"type": "number", "minimum": 0},
"development_time": {"type": "number", "minimum": 1}
}
}
}
},
DecisionType.PRICING: {
"type": "object",
"required": ["product_id", "price"],
"properties": {
"product_id": {"type": "string"},
"price": {"type": "number", "minimum": 0}
}
},
DecisionType.MARKETING: {
"type": "object",
"required": ["marketing_data"],
"properties": {
"marketing_data": {
"type": "object",
"required": ["budget"],
"properties": {
"budget": {"type": "number", "minimum": 0},
"target_segments": {
"type": "array",
"items": {"type": "string"}
},
"channels": {
"type": "object",
"properties": {
"tv": {"type": "number", "minimum": 0},
"online": {"type": "number", "minimum": 0},
"print": {"type": "number", "minimum": 0},
"radio": {"type": "number", "minimum": 0},
"social_media": {"type": "number", "minimum": 0}
}
},
"message": {"type": "string"},
"duration": {"type": "number", "minimum": 1}
}
}
}
},
DecisionType.RESOURCE_ALLOCATION: {
"type": "object",
"required": ["allocations"],
"properties": {
"allocations": {
"type": "object",
"properties": {
"r_and_d": {
"type": "object",
"properties": {
"change": {"type": "number"},
"efficiency_change": {"type": "number"},
"cost": {"type": "number", "minimum": 0}
}
},
"production": {
"type": "object",
"properties": {
"change": {"type": "number"},
"efficiency_change": {"type": "number"},
"cost": {"type": "number", "minimum": 0}
}
},
"marketing": {
"type": "object",
"properties": {
"change": {"type": "number"},
"efficiency_change": {"type": "number"},
"cost": {"type": "number", "minimum": 0}
}
},
"hr": {
"type": "object",
"properties": {
"change": {"type": "number"},
"efficiency_change": {"type": "number"},
"cost": {"type": "number", "minimum": 0}
}
}
}
}
}
},
DecisionType.INVESTMENT: {
"type": "object",
"required": ["investment_data"],
"properties": {
"investment_data": {
"type": "object",
"required": ["amount", "type"],
"properties": {
"amount": {"type": "number", "minimum": 0},
"type": {"type": "string", "enum": ["stocks", "bonds", "real_estate", "general"]},
"periods": {"type": "number", "minimum": 1}
}
}
}
},
DecisionType.PRODUCTION: {
"type": "object",
"required": ["production_data"],
"properties": {
"production_data": {
"type": "object",
"required": ["product_id", "quantity"],
"properties": {
"product_id": {"type": "string"},
"quantity": {"type": "number", "minimum": 0},
"quality_focus": {"type": "number", "minimum": 0, "maximum": 1},
"efficiency_focus": {"type": "number", "minimum": 0, "maximum": 1}
}
}
}
},
DecisionType.HUMAN_RESOURCES: {
"type": "object",
"required": ["hr_data"],
"properties": {
"hr_data": {
"type": "object",
"properties": {
"hiring": {
"type": "object",
"properties": {
"quantity": {"type": "number"},
"quality_level": {"type": "number", "minimum": 1, "maximum": 10},
"department": {"type": "string"}
}
},
"training": {
"type": "object",
"properties": {
"budget": {"type": "number", "minimum": 0},
"focus_area": {"type": "string"}
}
},
"compensation": {
"type": "object",
"properties": {
"change_percentage": {"type": "number"},
"bonus_budget": {"type": "number", "minimum": 0}
}
}
}
}
}
},
DecisionType.RESEARCH_DEVELOPMENT: {
"type": "object",
"required": ["rd_data"],
"properties": {
"rd_data": {
"type": "object",
"required": ["budget"],
"properties": {
"budget": {"type": "number", "minimum": 0},
"focus_areas": {
"type": "array",
"items": {"type": "string"}
},
"risk_level": {"type": "number", "minimum": 0, "maximum": 1},
"expected_completion": {"type": "number", "minimum": 1}
}
}
}
},
DecisionType.SUPPLY_CHAIN: {
"type": "object",
"required": ["supply_chain_data"],
"properties": {
"supply_chain_data": {
"type": "object",
"properties": {
"supplier_changes": {
"type": "array",
"items": {
"type": "object",
"properties": {
"supplier_id": {"type": "string"},
"action": {"type": "string", "enum": ["add", "remove", "modify"]},
"cost_change": {"type": "number"},
"quality_change": {"type": "number"}
}
}
},
"logistics_investment": {"type": "number", "minimum": 0},
"inventory_policy": {
"type": "object",
"properties": {
"target_level": {"type": "number", "minimum": 0},
"safety_stock": {"type": "number", "minimum": 0}
}
}
}
}
}
},
DecisionType.EXPANSION: {
"type": "object",
"required": ["expansion_data"],
"properties": {
"expansion_data": {
"type": "object",
"required": ["type", "investment"],
"properties": {
"type": {"type": "string", "enum": ["new_market", "new_facility", "acquisition"]},
"investment": {"type": "number", "minimum": 0},
"target_market": {"type": "string"},
"expected_return": {"type": "number"},
"risk_level": {"type": "number", "minimum": 0, "maximum": 1}
}
}
}
}
}
return schemas.get(decision_type, {"type": "object"})
class DecisionImpactCalculator:
"""Calculates the potential impact of decisions before they are made."""
@staticmethod
def calculate_potential_impact(decision_type: DecisionType,
decision_data: Dict[str, Any],
company_state: Dict[str, Any],
market_conditions: Dict[str, Any]) -> Dict[str, Any]:
"""
Calculate the potential impact of a decision.
Args:
decision_type: Type of decision
decision_data: Decision parameters
company_state: Current company state
market_conditions: Current market conditions
Returns:
Dict containing potential impact metrics
"""
impact = {
"financial_impact": 0,
"market_impact": 0,
"operational_impact": 0,
"risk_level": 0,
"details": {}
}
if decision_type == DecisionType.PRODUCT_DEVELOPMENT:
return DecisionImpactCalculator._calculate_product_development_impact(
decision_data, company_state, market_conditions)
elif decision_type == DecisionType.PRICING:
return DecisionImpactCalculator._calculate_pricing_impact(
decision_data, company_state, market_conditions)
elif decision_type == DecisionType.MARKETING:
return DecisionImpactCalculator._calculate_marketing_impact(
decision_data, company_state, market_conditions)
elif decision_type == DecisionType.RESOURCE_ALLOCATION:
return DecisionImpactCalculator._calculate_resource_allocation_impact(
decision_data, company_state, market_conditions)
elif decision_type == DecisionType.INVESTMENT:
return DecisionImpactCalculator._calculate_investment_impact(
decision_data, company_state, market_conditions)
return impact
@staticmethod
def _calculate_product_development_impact(decision_data: Dict[str, Any],
company_state: Dict[str, Any],
market_conditions: Dict[str, Any]) -> Dict[str, Any]:
"""Calculate impact of product development decision."""
product_data = decision_data.get("product_data", {})
# Extract key parameters
quality_level = product_data.get("quality_level", 1)
innovation_level = product_data.get("innovation_level", 1)
development_cost = product_data.get("development_cost", 100000)
production_cost = product_data.get("production_cost", 50)
selling_price = product_data.get("selling_price", 100)
category = product_data.get("category", "general")
# Calculate development cost
quality_factor = quality_level ** 1.5
innovation_factor = innovation_level ** 1.2
total_cost = development_cost * quality_factor * innovation_factor
# Calculate success probability
r_and_d_level = company_state.get("resources", {}).get("r_and_d", {}).get("level", 0)
success_prob = 0.7 + (0.2 * (r_and_d_level / 10))
success_prob = min(0.95, success_prob)
# Calculate potential market impact
segment_size = market_conditions.get("segment_sizes", {}).get(category, 0)
consumer_preferences = market_conditions.get("consumer_preferences", {}).get(category, {})
quality_sensitivity = consumer_preferences.get("quality_sensitivity", 0.5)
price_sensitivity = consumer_preferences.get("price_sensitivity", 0.5)
# Calculate market share potential
market_share_potential = segment_size * quality_sensitivity * price_sensitivity
# Calculate financial impact
revenue_potential = market_share_potential * selling_price
cost_potential = production_cost * (1 + quality_sensitivity)
profit_potential = revenue_potential - cost_potential
# Calculate operational impact
production_capacity = company_state.get("production", {}).get("capacity", 0)
production_efficiency = company_state.get("production", {}).get("efficiency", 0)
production_cost = company_state.get("production", {}).get("cost", 0)
# Calculate risk level
risk_level = 0.5 * (quality_sensitivity + price_sensitivity)
# Calculate financial impact
financial_impact = profit_potential * production_capacity * production_efficiency
# Calculate market impact
market_impact = market_share_potential * selling_price
# Calculate operational impact
operational_impact = production_capacity * production_efficiency
# Calculate risk level
risk_level = 0.5 * (quality_sensitivity + price_sensitivity)
# Calculate details
details = {
"revenue_potential": revenue_potential,
"cost_potential": cost_potential,
"profit_potential": profit_potential,
"production_capacity": production_capacity,
}
# Key Features for Business Simulation Web App
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:
## 1. Multi-functional Business Simulation
- **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
## 2. Realistic Market Dynamics
- **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
## 3. Strategic Decision Making
- **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
## 4. Financial Management
- **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
## 5. Marketing and Sales
- **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
## 6. Operations and Supply Chain
- **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
## 7. Human Resources
- **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
## 8. Learning and Feedback
- **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
## 9. User Experience
- **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
## 10. Multiplayer and Social Elements
- **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
—————
# Business Simulation Web App Requirements
This document outlines the technical and functional requirements for developing a comprehensive business simulation web application based on the analysis of existing solutions.
## Functional Requirements
### 1. Simulation Engine
- **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
### 2. Decision Management
- **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)
### 3. Data Management
- **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)
### 4. User Management
- **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)
### 5. Learning Components
- **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
### 6. Multiplayer Capabilities
- **Competitive Environment**
- Leaderboards and rankings
- Performance comparisons
- Tournament capabilities
- **Collaborative Features**
- Team-based decision making
- Role assignment within teams
- Communication tools for team members
## Technical Requirements
### 1. Architecture
- **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
### 2. Performance
- **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
### 3. Security
- **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
### 4. Integration
- **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
### 5. Deployment
- **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
## Non-functional Requirements
### 1. Usability
- Intuitive user interface requiring minimal training
- Clear visualization of complex business data
- Consistent design language across all features
- Accessibility compliance for diverse users
### 2. Reliability
- System availability of 99.9% during active hours
- Data persistence and recovery mechanisms
- Graceful handling of unexpected errors
### 3. Extensibility
- Modular design allowing for new simulation scenarios
- Ability to add new industries and business contexts
- Customizable metrics and performance indicators
### 4. Documentation
- Comprehensive user documentation and help resources
- Technical documentation for maintenance and extensions
- API documentation for potential integrations
————-
# Business Simulation Applications Analysis
This document provides a detailed analysis of various business simulation applications to identify their key features, strengths, and unique selling points.
## 1. Cesim
**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
## 2. SimulTrain
**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
## 3. Marketplace Simulations
**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
## 4. Glo-Bus
**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
## 5. Capsim
**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
## 6. Innov8 (IBM)
**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
## 7. Virtonomics
**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
## 8. Business Strategy Game (BSG) Online
**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
## 9. Simbound
**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
## 10. MonsoonSim
**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
## 11. PracticeEdu
**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
## 12. Simformer
**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
## 13. Forio
**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
———
# Implementation Guidelines for Business Simulation Web App
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.
## Table of Contents
1. [Project Overview](#project-overview)
2. [Technology Stack](#technology-stack)
3. [Project Structure](#project-structure)
4. [Simulation Engine Implementation](#simulation-engine-implementation)
5. [Frontend Implementation](#frontend-implementation)
6. [Database Schema](#database-schema)
7. [API Endpoints](#api-endpoints)
8. [Authentication and User Management](#authentication-and-user-management)
9. [Deployment Guidelines](#deployment-guidelines)
10. [Testing Strategy](#testing-strategy)
11. [Performance Considerations](#performance-considerations)
12. [Future Enhancements](#future-enhancements)
## Project Overview
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:
1. A robust simulation engine that models business dynamics
2. An intuitive user interface for decision-making and analysis
## Technology Stack
### Backend
- **Framework**: Next.js with API routes
- **Runtime**: Node.js
- **Database**: Cloudflare D1 (SQLite-compatible)
- **ORM**: Prisma (optional)
- **Authentication**: NextAuth.js
### Frontend
- **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
### Development Tools
- **Package Manager**: pnpm
- **Version Control**: Git
- **Linting**: ESLint
- **Formatting**: Prettier
- **Testing**: Jest, React Testing Library
## Project Structure
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
```
## Simulation Engine Implementation
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.
### Core Components
1. **SimulationEngine**: The main class that orchestrates the simulation process.
2. **Company**: Represents a company in the simulation with properties and methods.
3. **Market**: Models market dynamics, consumer behavior, and competitive forces.
4. **DecisionProcessor**: Processes user decisions and applies them to the simulation.
5. **PerformanceCalculator**: Calculates performance metrics based on decisions and market conditions.
6. **EventGenerator**: Generates random events that affect the simulation.
### Implementation Steps
1. **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:
```typescript
// 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();
}
}
```
2. **Implement Market Dynamics**:
- Convert the `MarketSimulator`, `MarketTrends`, `ConsumerBehavior`, and `CompetitiveDynamics` classes.
- Ensure proper integration with the core simulation engine.
3. **Implement Decision Processing**:
- Convert the decision types and schemas to TypeScript interfaces.
- Implement the decision processing logic to handle different types of decisions.
4. **Implement Performance Calculation**:
- Develop algorithms to calculate financial and operational performance metrics.
- Ensure proper integration with the market and company models.
5. **Implement Event Generation**:
- Create a system for generating random events that affect the simulation.
- Define event types, probabilities, and impact calculations.
6. **Create Database Integration**:
- Implement functions to store and retrieve simulation state from the database.
- Ensure proper transaction handling for consistency.
7. **Develop API Layer**:
- Create API endpoints to interact with the simulation engine.
- Implement proper error handling and validation.
## Frontend Implementation
The frontend provides the user interface for interacting with the simulation. It consists of multiple pages and components organized by functionality.
### Key Pages
1. **Dashboard**: Provides an overview of company performance and key metrics.
2. **Market Analysis**: Displays market conditions, trends, and competitor analysis.
3. **Product Management**: Allows users to manage products and view product performance.
4. **Decision Making**: Interfaces for making various business decisions.
5. **Reports**: Detailed reports and visualizations of performance data.
### Implementation Steps
1. **Set Up Next.js Project**:
- Create a new Next.js project using the provided command.
- Configure Tailwind CSS and other dependencies.
```bash
create_nextjs_app business_simulation_app
cd business_simulation_app
```
2. **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:
```tsx
// 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>
);
}
```
3. **Implement Dashboard Page**:
- Create the dashboard layout based on the mockup.
- Implement charts and statistics components.
- Connect to the API to fetch real data.
```tsx
// 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>
);
}
```
4. **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.
5. **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.
6. **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.
7. **Implement Authentication and User Management**:
- Set up NextAuth.js for authentication.
- Create login, registration, and profile pages.
- Implement role-based access control if needed.
8. **Implement Data Visualization**:
- Use Recharts to create interactive charts and graphs.
- Ensure responsive design for different screen sizes.
Example of a performance chart component:
```tsx
// 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>
);
}
```
## Database Schema
The application uses Cloudflare D1 (SQLite-compatible) for data storage. The database schema is defined in migration files and includes the following tables:
### Users Table
```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
);
```
### Simulations Table
```sql
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);
```
### Simulations Table
Stores simulation configurations and state.
```sql
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);
```
### Simulation Users Table
Stores the relationship between users and simulations (many-to-many).
```sql
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);
```
### Companies Table
Stores company data for each user in a simulation.
```sql
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);
```
### Products Table
Stores product information for each company.
```sql
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);
```
### Decisions Table
Stores decisions made by users for their companies.
```sql
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);
```
### Market Conditions Table
Stores market conditions for each period.
```sql
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);
```
### Performance Results Table
Stores performance metrics for each company in each period.
```sql
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);
```
### Product Performance Table
Stores performance metrics for each product in each period.
```sql
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);
```
### Events Table
Stores random events that occur during the simulation.
```sql
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);
```
### Transactions Table
Stores financial transactions for each company.
```sql
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);
```
### Research Projects Table
Stores R&D projects for each company.
```sql
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);
```
### Human Resources Table
Stores human resources data for each company.
```sql
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);
```
### Marketing Campaigns Table
Stores marketing campaigns for each company.
```sql
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);
```
### Competitor Actions Table
Stores actions taken by simulated competitors.
```sql
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
Database migrations are managed using Wrangler's D1 migration system. Migrations are stored in the `migrations` directory and applied using the Wrangler CLI.
### Initial Migration
The initial migration creates all the tables defined above:
```sql
-- 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:
```
http://localhost:3000/api
```
## 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 <token>
```
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
}
}
```
### Error Response
```json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error message",
"details": {
// Optional additional error details
}
}
}
```
## Common Error Codes
| 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 |
## API Endpoints
### Authentication
#### Register a new user
```
POST /auth/register
```
**Request Body:**
```json
{
"name": "John Doe",
"email": "[email protected]",
"password": "securepassword123"
}
```
**Response:**
```json
{
"success": true,
"data": {
"user": {
"id": "user_123",
"name": "John Doe",
"email": "[email protected]",
"role": "user"
}
}
}
```
#### Log in
```
POST /auth/login
```
**Request Body:**
```json
{
"email": "[email protected]",
"password": "securepassword123"
}
```
**Response:**
```json
{
"success": true,
"data": {
"user": {
"id": "user_123",
"name": "John Doe",
"email": "[email protected]",
"role": "user"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
```
#### Get current session
```
GET /auth/session
```
**Response:**
```json
{
"success": true,
"data": {
"user": {
"id": "user_123",
"name": "John Doe",
"email": "[email protected]",
"role": "user"
}
}
}
```
#### Log out
```
GET /auth/logout
```
**Response:**
```json
{
"success": true,
"data": {
"message": "Logged out successfully"
}
}
```
### Simulations
#### Get all simulations
```
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:**
```json
{
"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
}
}
```
#### Create a new simulation
```
POST /simulations
```
**Request Body:**
```json
{
"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:**
```json
{
"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 a specific simulation
```
GET /simulations/:id
```
**Path Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | string | Simulation ID |
**Response:**
```json
{
"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
}
}
}
}
```
#### Update a simulation
```
PUT /simulations/:id
```
**Path Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | string | Simulation ID |
**Request Body:**
```json
{
"name": "Updated Simulation Name",
"description": "Updated description",
"status": "paused"
}
```
**Response:**
```json
{
"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 a simulation
```
DELETE /simulations/:id
```
**Path Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | string | Simulation ID |
**Response:**
```json
{
"success": true,
"data": {
"message": "Simulation deleted successfully"
}
}
```
#### Join a simulation
```
POST /simulations/:id/join
```
**Path Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | string | Simulation ID |
**Request Body:**
```json
{
"role": "participant" // Optional, defaults to "participant"
}
```
**Response:**
```json
{
"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"
}
}
}
```
#### Advance to the next period
```
POST /simulations/:id/advance
```
**Path Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | string | Simulation ID |
**Response:**
```json
{
"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...
}
}
}
```
### Companies
#### Get all companies for the current user
```
GET /companies
```
**Query Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `simulation_id` | string | Filter by simulation ID |
**Response:**
```json
{
"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...
]
}
}
```
#### Create a new company
```
POST /companies
```
**Request Body:**
```json
{
"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:**
```json
{
"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 a specific company
```
GET /companies/:id
```
**Path Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | string | Company ID |
**Response:**
```json
{
"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"
}
}
}
}
```
#### Update a company
```
PUT /companies/:id
```
**Path Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | string | Company ID |
**Request Body:**
```json
{
"name": "TechInnovate Global",
"description": "A global technology innovation company",
"data": {
"mission_statement": "To innovate and transform technology globally",
"values": ["Innovation", "Integrity", "Excellence"]
}
}
```
**Response:**
```json
{
"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 a company
```
DELETE /companies/:id
```
**Path Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | string | Company ID |
**Response:**
```json
{
"success": true,
"data": {
"message": "Company deleted successfully"
}
}
```
### Products
#### Get all products for a company
```
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:**
```json
{
"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...
]
}
}
```
#### Create a new product
```
POST /products
```
**Request Body:**
```json
{
"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:**
```json
{
"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 a specific product
```
GET /products/:id
```
**Path Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `id` | string | Product ID |
**Response:**
```json
{
"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
"""
Business Simulation Market Dynamics
==================================
This module provides market simulation functionality, including market trends,
consumer behavior, and competitive dynamics.
"""
import random
import math
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple
class MarketSimulator:
"""Simulates market dynamics and consumer behavior."""
def __init__(self, config: Dict[str, Any]):
"""
Initialize the market simulator.
Args:
config: Market configuration parameters
"""
self.config = config
self.segments = config.get('segments', ['budget', 'mid-range', 'premium'])
self.total_market_size = config.get('initial_market_size', 1000000)
self.growth_rate = config.get('growth_rate', 0.05)
self.segment_distribution = config.get('segment_distribution',
{'budget': 0.5, 'mid-range': 0.3, 'premium': 0.2})
self.price_sensitivity = config.get('price_sensitivity',
{'budget': 0.8, 'mid-range': 0.5, 'premium': 0.3})
self.quality_sensitivity = config.get('quality_sensitivity',
{'budget': 0.2, 'mid-range': 0.5, 'premium': 0.7})
self.brand_sensitivity = config.get('brand_sensitivity',
{'budget': 0.3, 'mid-range': 0.5, 'premium': 0.7})
self.innovation_sensitivity = config.get('innovation_sensitivity',
{'budget': 0.2, 'mid-range': 0.4, 'premium': 0.6})
self.market_trends = MarketTrends(config.get('trends_config', {}))
self.consumer_behavior = ConsumerBehavior(config.get('consumer_config', {}))
self.competitive_dynamics = CompetitiveDynamics(config.get('competition_config', {}))
def generate_market_conditions(self, period: int) -> Dict[str, Any]:
"""
Generate market conditions for a specific period.
Args:
period: The period number
Returns:
Dict containing market conditions
"""
# Calculate market growth
growth_factor = (1 + self.growth_rate) ** period
current_market_size = self.total_market_size * growth_factor
# Get market trends for this period
trends = self.market_trends.get_trends(period)
# Apply trend effects to market size
trend_growth_factor = 1 + trends.get('market_growth_impact', 0)
current_market_size *= trend_growth_factor
# Apply trend effects to segment distribution
segment_distribution = {}
for segment in self.segments:
base_distribution = self.segment_distribution.get(segment, 1.0 / len(self.segments))
# Apply trend effects
segment_trend_factor = 1 + trends.get('segment_shifts', {}).get(segment, 0)
# Add random variation (±10%)
random_factor = 1 + (random.random() * 0.2 - 0.1)
segment_distribution[segment] = base_distribution * segment_trend_factor * random_factor
# Normalize to ensure sum is 1.0
total = sum(segment_distribution.values())
segment_distribution = {k: v / total for k, v in segment_distribution.items()}
# Calculate segment sizes
segment_sizes = {segment: current_market_size * dist
for segment, dist in segment_distribution.items()}
# Generate consumer preferences
consumer_preferences = self.consumer_behavior.generate_preferences(
self.segments, self.price_sensitivity, self.quality_sensitivity,
self.brand_sensitivity, self.innovation_sensitivity, trends)
# Generate economic indicators
economic_indicators = self._generate_economic_indicators(period, trends)
return {
'period': period,
'timestamp': datetime.now().isoformat(),
'total_market_size': current_market_size,
'segment_distribution': segment_distribution,
'segment_sizes': segment_sizes,
'consumer_preferences': consumer_preferences,
'economic_indicators': economic_indicators,
'market_trends': trends
}
def calculate_market_shares(self, products: List[Dict[str, Any]],
market_conditions: Dict[str, Any]) -> Dict[str, float]:
"""
Calculate market shares for products based on market conditions.
Args:
products: List of products from all companies
market_conditions: Current market conditions
Returns:
Dict mapping product IDs to market share percentages
"""
# Group products by segment
segment_products = {}
for product in products:
segment = product.get('category', 'general')
if segment not in segment_products:
segment_products[segment] = []
segment_products[segment].append(product)
# Calculate attractiveness and market share within each segment
market_shares = {}
for segment, segment_products_list in segment_products.items():
# Get segment-specific consumer preferences
preferences = market_conditions.get('consumer_preferences', {}).get(segment, {})
price_sensitivity = preferences.get('price_sensitivity', 0.5)
quality_sensitivity = preferences.get('quality_sensitivity', 0.5)
brand_sensitivity = preferences.get('brand_loyalty', 0.3)
innovation_sensitivity = preferences.get('innovation_preference', 0.4)
# Calculate attractiveness for each product
product_attractiveness = {}
for product in segment_products_list:
price_score = 1 - (product.get('selling_price', 100) / 200) # Normalize price
quality_score = product.get('quality_rating', 1) / 10 # Normalize quality
brand_score = product.get('brand_rating', 1) / 10 # Normalize brand
innovation_score = product.get('innovation_rating', 1) / 10 # Normalize innovation
# Weight scores by consumer preferences
attractiveness = (
price_score * price_sensitivity +
quality_score * quality_sensitivity +
brand_score * brand_sensitivity +
innovation_score * innovation_sensitivity
)
product_attractiveness[product['id']] = attractiveness
# Calculate market share based on relative attractiveness
total_attractiveness = sum(product_attractiveness.values())
if total_attractiveness > 0:
segment_size = market_conditions.get('segment_sizes', {}).get(segment, 0)
for product_id, attractiveness in product_attractiveness.items():
market_share = attractiveness / total_attractiveness
market_shares[product_id] = {
'segment_share': market_share,
'overall_share': market_share * segment_size / market_conditions.get('total_market_size', 1),
'segment': segment,
'attractiveness': attractiveness
}
return market_shares
def simulate_competitive_response(self, company_actions: Dict[str, List[Dict[str, Any]]],
market_conditions: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
"""
Simulate competitive responses to company actions.
Args:
company_actions: Dictionary mapping company IDs to their actions
market_conditions: Current market conditions
Returns:
Dict mapping company IDs to their competitive responses
"""
return self.competitive_dynamics.generate_responses(company_actions, market_conditions)
def _generate_economic_indicators(self, period: int, trends: Dict[str, Any]) -> Dict[str, float]:
"""
Generate economic indicators for a period.
Args:
period: The period number
trends: Market trends for the period
Returns:
Dict containing economic indicators
"""
# Base economic cycle (simplified)
cycle_length = 12 # periods
cycle_position = period % cycle_length
cycle_factor = math.sin(cycle_position / cycle_length * 2 * math.pi)
# Apply trend effects
economic_trend = trends.get('economic_trend', 0)
# Generate indicators with cyclical patterns and trend effects
gdp_growth = 0.02 + (0.03 * cycle_factor) + economic_trend
inflation_rate = 0.02 + (0.02 * -cycle_factor) + (economic_trend / 2)
unemployment_rate = 0.05 + (0.03 * -cycle_factor) - (economic_trend * 2)
interest_rate = 0.03 + (0.02 * -cycle_factor) + (inflation_rate / 2)
# Add some randomness
gdp_growth += random.uniform(-0.01, 0.01)
inflation_rate += random.uniform(-0.005, 0.005)
unemployment_rate += random.uniform(-0.01, 0.01)
interest_rate += random.uniform(-0.005, 0.005)
# Ensure reasonable bounds
unemployment_rate = max(0.02, min(0.15, unemployment_rate))
inflation_rate = max(0, min(0.15, inflation_rate))
interest_rate = max(0.01, min(0.15, interest_rate))
return {
'gdp_growth': gdp_growth,
'inflation_rate': inflation_rate,
'unemployment_rate': unemployment_rate,
'interest_rate': interest_rate,
'consumer_confidence': 0.5 + (0.3 * cycle_factor) + (economic_trend * 2) + random.uniform(-0.1, 0.1)
}
class MarketTrends:
"""Generates and manages market trends over time."""
def __init__(self, config: Dict[str, Any]):
"""
Initialize market trends.
Args:
config: Trends configuration parameters
"""
self.config = config
self.trend_change_probability = config.get('trend_change_probability', 0.2)
self.trend_strength = config.get('trend_strength', 0.1)
self.current_trends = self._initialize_trends()
self.trend_history = []
def get_trends(self, period: int) -> Dict[str, Any]:
"""
Get market trends for a specific period.
Args:
period: The period number
Returns:
Dict containing market trends
"""
# Update trends if needed
if period >= len(self.trend_history):
self._update_trends(period)
# Return trends for the period
if period < len(self.trend_history):
return self.trend_history[period]
else:
# Fallback to current trends
return self.current_trends
def _initialize_trends(self) -> Dict[str, Any]:
"""
Initialize starting market trends.
Returns:
Dict containing initial trends
"""
return {
'market_growth_impact': 0,
'segment_shifts': {
'budget': 0,
'mid-range': 0,
'premium': 0
},
'consumer_preference_shifts': {
'price_sensitivity': 0,
'quality_sensitivity': 0,
'brand_loyalty': 0,
'innovation_preference': 0
},
'economic_trend': 0,
'technology_trends': [],
'sustainability_importance': 0.3 + random.uniform(-0.1, 0.1)
}
def _update_trends(self, period: int) -> None:
"""
Update market trends for a new period.
Args:
period: The period number
"""
# Ensure trend history is up to date
while len(self.trend_history) < period:
# Copy previous trends or initialize if first period
if self.trend_history:
previous_trends = self.trend_history[-1].copy()
else:
previous_trends = self.current_trends.copy()
# Apply random changes to trends
new_trends = self._evolve_trends(previous_trends)
# Add to history
self.trend_history.append(new_trends)
# Update current trends
self.current_trends = new_trends
def _evolve_trends(self, previous_trends: Dict[str, Any]) -> Dict[str, Any]:
"""
Evolve trends from previous period.
Args:
previous_trends: Trends from previous period
Returns:
Dict containing evolved trends
"""
new_trends = previous_trends.copy()
# Evolve market growth impact
if random.random() < self.trend_change_probability:
# Shift direction
new_trends['market_growth_impact'] += random.uniform(-self.trend_strength, self.trend_strength)
# Limit range
new_trends['market_growth_impact'] = max(-0.2, min(0.2, new_trends['market_growth_impact']))
# Evolve segment shifts
for segment in new_trends['segment_shifts']:
if random.random() < self.trend_change_probability:
new_trends['segment_shifts'][segment] += random.uniform(-self.trend_strength, self.trend_strength)
# Limit range
new_trends['segment_shifts'][segment] = max(-0.3, min(0.3, new_trends['segment_shifts'][segment]))
# Evolve consumer preference shifts
for preference in new_trends['consumer_preference_shifts']:
if random.random() < self.trend_change_probability:
new_trends['consumer_preference_shifts'][preference] += random.uniform(-self.trend_strength/2, self.trend_strength/2)
# Limit range
new_trends['consumer_preference_shifts'][preference] = max(-0.2, min(0.2, new_trends['consumer_preference_shifts'][preference]))
# Evolve economic trend
if random.random() < self.trend_change_probability:
new_trends['economic_trend'] += random.uniform(-self.trend_strength, self.trend_strength)
# Limit range
new_trends['economic_trend'] = max(-0.1, min(0.1, new_trends['economic_trend']))
# Evolve technology trends
if random.random() < self.trend_change_probability:
# Potentially add new technology trend
if random.random() < 0.3 and len(new_trends['technology_trends']) < 3:
new_tech = self._generate_technology_trend()
new_trends['technology_trends'].append(new_tech)
# Potentially remove old technology trend
if random.random() < 0.2 and new_trends['technology_trends']:
new_trends['technology_trends'].pop(0)
# Evolve sustainability importance
if random.random() < self.trend_change_probability:
# Generally increasing over time with some fluctuation
new_trends['sustainability_importance'] += random.uniform(-0.05, 0.1)
# Limit range
new_trends['sustainability_importance'] = max(0.1, min(0.9, new_trends['sustainability_importance']))
return new_trends
def _generate_technology_trend(self) -> Dict[str, Any]:
"""
Generate a new technology trend.
Returns:
Dict containing technology trend details
"""
# Randomly select a technology type
technology_types = ['AI', 'Blockchain', 'Cloud Computing', 'Internet of Things', 'Robotics']
technology_type = random.choice(technology_types)
return {
'type': technology_type,
'impact': random.uniform(-0.1, 0.1),
'trend_duration': random.randint(1, 3) # Number of periods the trend lasts
}
"""
Business Simulation Engine Core
==============================
This module provides the core functionality for the business simulation engine.
It includes classes for managing simulation state, processing decisions, and
calculating outcomes based on business logic.
"""
import json
import random
import math
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple
class SimulationEngine:
"""Main simulation engine that coordinates all simulation components."""
def __init__(self, config: Dict[str, Any]):
"""
Initialize the simulation engine with configuration.
Args:
config: Dictionary containing simulation configuration parameters
"""
self.config = config
self.current_period = 0
self.max_periods = config.get('max_periods', 12)
self.companies = {}
self.market = Market(config.get('market_config', {}))
self.decision_processor = DecisionProcessor()
self.performance_calculator = PerformanceCalculator()
self.event_generator = EventGenerator(config.get('event_config', {}))
self.is_initialized = False
def initialize_simulation(self) -> None:
"""Set up the initial state of the simulation."""
self.current_period = 0
self.is_initialized = True
self.market.initialize_market()
def register_company(self, company_id: str, company_data: Dict[str, Any]) -> None:
"""
Register a company in the simulation.
Args:
company_id: Unique identifier for the company
company_data: Initial company data
"""
self.companies[company_id] = Company(company_id, company_data)
def process_period(self) -> Dict[str, Any]:
"""
Process a complete simulation period.
Returns:
Dict containing the results of the period processing
"""
if not self.is_initialized:
raise RuntimeError("Simulation must be initialized before processing periods")
if self.current_period >= self.max_periods:
return {"status": "completed", "message": "Simulation has reached maximum periods"}
# Generate market conditions for the period
market_conditions = self.market.generate_market_conditions(self.current_period)
# Generate random events for the period
period_events = self.event_generator.generate_events(self.current_period, market_conditions)
# Process decisions for each company
for company_id, company in self.companies.items():
decisions = company.get_pending_decisions()
processed_decisions = self.decision_processor.process_decisions(
decisions,
company,
market_conditions,
period_events
)
company.apply_processed_decisions(processed_decisions)
# Calculate performance for each company
for company_id, company in self.companies.items():
performance = self.performance_calculator.calculate_performance(
company,
market_conditions,
self.companies # Pass all companies for competitive analysis
)
company.update_performance(performance)
# Update market based on company actions
self.market.update_market(self.companies, period_events)
# Advance to next period
self.current_period += 1
return {
"status": "success",
"period": self.current_period - 1,
"market_conditions": market_conditions,
"events": period_events,
"companies": {cid: c.get_public_data() for cid, c in self.companies.items()}
}
def get_simulation_state(self) -> Dict[str, Any]:
"""
Get the current state of the simulation.
Returns:
Dict containing the current simulation state
"""
return {
"current_period": self.current_period,
"max_periods": self.max_periods,
"is_initialized": self.is_initialized,
"market": self.market.get_state(),
"companies": {cid: c.get_state() for cid, c in self.companies.items()},
"config": self.config
}
def load_simulation_state(self, state: Dict[str, Any]) -> None:
"""
Load a simulation state.
Args:
state: Dictionary containing simulation state to load
"""
self.current_period = state.get("current_period", 0)
self.max_periods = state.get("max_periods", 12)
self.is_initialized = state.get("is_initialized", False)
self.config = state.get("config", {})
# Load market state
self.market = Market(self.config.get('market_config', {}))
self.market.load_state(state.get("market", {}))
# Load companies
self.companies = {}
for company_id, company_state in state.get("companies", {}).items():
company = Company(company_id, {})
company.load_state(company_state)
self.companies[company_id] = company
class Company:
"""Represents a company in the simulation."""
def __init__(self, company_id: str, initial_data: Dict[str, Any]):
"""
Initialize a company.
Args:
company_id: Unique identifier for the company
initial_data: Initial company data
"""
self.id = company_id
self.name = initial_data.get('name', f"Company {company_id}")
self.cash = initial_data.get('initial_cash', 1000000.0)
self.products = initial_data.get('products', [])
self.resources = initial_data.get('resources', {})
self.pending_decisions = []
self.decision_history = []
self.performance_history = []
def add_decision(self, decision: Dict[str, Any]) -> None:
"""
Add a pending decision for the company.
Args:
decision: Decision data
"""
decision['timestamp'] = datetime.now().isoformat()
decision['status'] = 'pending'
self.pending_decisions.append(decision)
def get_pending_decisions(self) -> List[Dict[str, Any]]:
"""
Get all pending decisions.
Returns:
List of pending decisions
"""
return self.pending_decisions
def apply_processed_decisions(self, processed_decisions: List[Dict[str, Any]]) -> None:
"""
Apply processed decisions to the company state.
Args:
processed_decisions: List of processed decisions with outcomes
"""
for decision in processed_decisions:
# Update decision status
decision['status'] = 'applied'
# Apply financial impact
if 'financial_impact' in decision:
self.cash += decision['financial_impact']
# Apply product changes
if decision['type'] == 'product_development' and 'product' in decision:
self._update_or_add_product(decision['product'])
# Apply resource changes
if decision['type'] == 'resource_allocation' and 'resources' in decision:
self._update_resources(decision['resources'])
# Add to decision history
self.decision_history.append(decision)
# Clear pending decisions
self.pending_decisions = []
def update_performance(self, performance: Dict[str, Any]) -> None:
"""
Update company performance metrics.
Args:
performance: Dictionary of performance metrics
"""
# Add timestamp
performance['timestamp'] = datetime.now().isoformat()
# Update cash based on profit/loss
if 'profit' in performance:
self.cash += performance['profit']
# Add to performance history
self.performance_history.append(performance)
def get_public_data(self) -> Dict[str, Any]:
"""
Get public-facing company data.
Returns:
Dict containing public company data
"""
# Return subset of data visible to other companies/players
return {
'id': self.id,
'name': self.name,
'products': [self._get_public_product_data(p) for p in self.products],
'market_share': self._calculate_market_share(),
'performance': self._get_latest_performance()
}
def get_state(self) -> Dict[str, Any]:
"""
Get complete company state.
Returns:
Dict containing complete company state
"""
return {
'id': self.id,
'name': self.name,
'cash': self.cash,
'products': self.products,
'resources': self.resources,
'pending_decisions': self.pending_decisions,
'decision_history': self.decision_history,
'performance_history': self.performance_history
}
def load_state(self, state: Dict[str, Any]) -> None:
"""
Load company state.
Args:
state: Dictionary containing company state to load
"""
self.id = state.get('id', self.id)
self.name = state.get('name', self.name)
self.cash = state.get('cash', self.cash)
self.products = state.get('products', self.products)
self.resources = state.get('resources', self.resources)
self.pending_decisions = state.get('pending_decisions', self.pending_decisions)
self.decision_history = state.get('decision_history', self.decision_history)
self.performance_history = state.get('performance_history', self.performance_history)
def _update_or_add_product(self, product: Dict[str, Any]) -> None:
"""
Update existing product or add new product.
Args:
product: Product data
"""
# Check if product already exists
for i, existing_product in enumerate(self.products):
if existing_product['id'] == product['id']:
# Update existing product
self.products[i] = product
return
# Add new product
self.products.append(product)
def _update_resources(self, resources: Dict[str, Any]) -> None:
"""
Update company resources.
Args:
resources: Resource allocation data
"""
for resource_type, allocation in resources.items():
if resource_type in self.resources:
self.resources[resource_type].update(allocation)
else:
self.resources[resource_type] = allocation
def _calculate_market_share(self) -> float:
"""
Calculate company's market share based on latest performance.
Returns:
Float representing market share percentage
"""
if not self.performance_history:
return 0.0
latest_performance = self.performance_history[-1]
return latest_performance.get('market_share', 0.0)
def _get_latest_performance(self) -> Dict[str, Any]:
"""
Get the latest performance metrics.
Returns:
Dict containing latest performance metrics
"""
if not self.performance_history:
return {}
return {k: v for k, v in self.performance_history[-1].items()
if k not in ['timestamp', 'detailed_metrics']}
def _get_public_product_data(self, product: Dict[str, Any]) -> Dict[str, Any]:
"""
Get public-facing product data.
Args:
product: Complete product data
Returns:
Dict containing public product data
"""
return {
'id': product['id'],
'name': product['name'],
'category': product['category'],
'quality_rating': product.get('quality_rating', 0),
'price': product.get('selling_price', 0)
}
class Market:
"""Represents the market environment in the simulation."""
def __init__(self, config: Dict[str, Any]):
"""
Initialize the market.
Args:
config: Market configuration parameters
"""
self.config = config
self.segments = config.get('segments', ['budget', 'mid-range', 'premium'])
self.total_market_size = config.get('initial_market_size', 1000000)
self.growth_rate = config.get('growth_rate', 0.05)
self.segment_distribution = config.get('segment_distribution',
{'budget': 0.5, 'mid-range': 0.3, 'premium': 0.2})
self.price_sensitivity = config.get('price_sensitivity',
{'budget': 0.8, 'mid-range': 0.5, 'premium': 0.3})
self.quality_sensitivity = config.get('quality_sensitivity',
{'budget': 0.2, 'mid-range': 0.5, 'premium': 0.7})
self.conditions_history = []
def initialize_market(self) -> None:
"""Initialize market conditions."""
initial_conditions = self.generate_market_conditions(0)
self.conditions_history.append(initial_conditions)
def generate_market_conditions(self, period: int) -> Dict[str, Any]:
"""
Generate market conditions for a specific period.
Args:
period: The period number
Returns:
Dict containing market conditions
"""
# Calculate market growth
growth_factor = (1 + self.growth_rate) ** period
current_market_size = self.total_market_size * growth_factor
# Add some randomness to segment distribution
segment_distribution = {}
for segment in self.segments:
base_distribution = self.segment_distribution.get(segment, 1.0 / len(self.segments))
# Add up to ±10% random variation
random_factor = 1 + (random.random() * 0.2 - 0.1)
segment_distribution[segment] = base_distribution * random_factor
# Normalize to ensure sum is 1.0
total = sum(segment_distribution.values())
segment_distribution = {k: v / total for k, v in segment_distribution.items()}
# Calculate segment sizes
segment_sizes = {segment: current_market_size * dist
for segment, dist in segment_distribution.items()}
# Generate consumer preferences
consumer_preferences = {}
for segment in self.segments:
consumer_preferences[segment] = {
'price_sensitivity': self.price_sensitivity.get(segment, 0.5),
'quality_sensitivity': self.quality_sensitivity.get(segment, 0.5),
# Add other preferences as needed
'brand_loyalty': random.uniform(0.1, 0.5),
'innovation_preference': random.uniform(0.2, 0.8)
}
# Generate economic indicators
economic_indicators = {
'gdp_growth': random.uniform(-0.02, 0.05),
'inflation_rate': random.uniform(0.01, 0.04),
'unemployment_rate': random.uniform(0.03, 0.08),
'interest_rate': random.uniform(0.02, 0.06)
}
conditions = {
'period': period,
'timestamp': datetime.now().isoformat(),
'market_size': current_market_size,
'segment_sizes': segment_sizes,
'consumer_preferences': consumer_preferences,
'economic_indicators': economic_indicators
}

Key Features for Business Simulation Web App

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:

1. Multi-functional Business Simulation

  • 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

2. Realistic Market Dynamics

  • 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

3. Strategic Decision Making

  • 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

4. Financial Management

  • 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

5. Marketing and Sales

  • 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

6. Operations and Supply Chain

  • 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

7. Human Resources

  • 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

8. Learning and Feedback

  • 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

9. User Experience

  • 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

10. Multiplayer and Social Elements

  • 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

—————

Business Simulation Web App Requirements

This document outlines the technical and functional requirements for developing a comprehensive business simulation web application based on the analysis of existing solutions.

Functional Requirements

1. Simulation Engine

  • 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

2. Decision Management

  • 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)

3. Data Management

  • 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)

4. User Management

  • 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)

5. Learning Components

  • 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

6. Multiplayer Capabilities

  • Competitive Environment

    • Leaderboards and rankings
    • Performance comparisons
    • Tournament capabilities
  • Collaborative Features

    • Team-based decision making
    • Role assignment within teams
    • Communication tools for team members

Technical Requirements

1. Architecture

  • 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

2. Performance

  • 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

3. Security

  • 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

4. Integration

  • 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

5. Deployment

  • 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

Non-functional Requirements

1. Usability

  • Intuitive user interface requiring minimal training
  • Clear visualization of complex business data
  • Consistent design language across all features
  • Accessibility compliance for diverse users

2. Reliability

  • System availability of 99.9% during active hours
  • Data persistence and recovery mechanisms
  • Graceful handling of unexpected errors

3. Extensibility

  • Modular design allowing for new simulation scenarios
  • Ability to add new industries and business contexts
  • Customizable metrics and performance indicators

4. Documentation

  • Comprehensive user documentation and help resources
  • Technical documentation for maintenance and extensions
  • API documentation for potential integrations

————-

Business Simulation Applications Analysis

This document provides a detailed analysis of various business simulation applications to identify their key features, strengths, and unique selling points.

1. Cesim

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

2. SimulTrain

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

3. Marketplace Simulations

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

4. Glo-Bus

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

5. Capsim

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

6. Innov8 (IBM)

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

7. Virtonomics

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

8. Business Strategy Game (BSG) Online

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

9. Simbound

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

10. MonsoonSim

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

11. PracticeEdu

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

12. Simformer

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

13. Forio

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 ———

Implementation Guidelines for Business Simulation Web App

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.

Table of Contents

  1. Project Overview
  2. Technology Stack
  3. Project Structure
  4. Simulation Engine Implementation
  5. Frontend Implementation
  6. Database Schema
  7. API Endpoints
  8. Authentication and User Management
  9. Deployment Guidelines
  10. Testing Strategy
  11. Performance Considerations
  12. Future Enhancements

Project Overview

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:

  1. A robust simulation engine that models business dynamics
  2. An intuitive user interface for decision-making and analysis

Technology Stack

Backend

  • Framework: Next.js with API routes
  • Runtime: Node.js
  • Database: Cloudflare D1 (SQLite-compatible)
  • ORM: Prisma (optional)
  • Authentication: NextAuth.js

Frontend

  • 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

Development Tools

  • Package Manager: pnpm
  • Version Control: Git
  • Linting: ESLint
  • Formatting: Prettier
  • Testing: Jest, React Testing Library

Project Structure

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

Simulation Engine Implementation

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.

Core Components

  1. SimulationEngine: The main class that orchestrates the simulation process.
  2. Company: Represents a company in the simulation with properties and methods.
  3. Market: Models market dynamics, consumer behavior, and competitive forces.
  4. DecisionProcessor: Processes user decisions and applies them to the simulation.
  5. PerformanceCalculator: Calculates performance metrics based on decisions and market conditions.
  6. EventGenerator: Generates random events that affect the simulation.

Implementation Steps

  1. 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();
  }
}
  1. Implement Market Dynamics:

    • Convert the MarketSimulator, MarketTrends, ConsumerBehavior, and CompetitiveDynamics classes.
    • Ensure proper integration with the core simulation engine.
  2. Implement Decision Processing:

    • Convert the decision types and schemas to TypeScript interfaces.
    • Implement the decision processing logic to handle different types of decisions.
  3. Implement Performance Calculation:

    • Develop algorithms to calculate financial and operational performance metrics.
    • Ensure proper integration with the market and company models.
  4. Implement Event Generation:

    • Create a system for generating random events that affect the simulation.
    • Define event types, probabilities, and impact calculations.
  5. Create Database Integration:

    • Implement functions to store and retrieve simulation state from the database.
    • Ensure proper transaction handling for consistency.
  6. Develop API Layer:

    • Create API endpoints to interact with the simulation engine.
    • Implement proper error handling and validation.

Frontend Implementation

The frontend provides the user interface for interacting with the simulation. It consists of multiple pages and components organized by functionality.

Key Pages

  1. Dashboard: Provides an overview of company performance and key metrics.
  2. Market Analysis: Displays market conditions, trends, and competitor analysis.
  3. Product Management: Allows users to manage products and view product performance.
  4. Decision Making: Interfaces for making various business decisions.
  5. Reports: Detailed reports and visualizations of performance data.

Implementation Steps

  1. 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
  1. 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>
  );
}
  1. 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>
  );
}
  1. 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.
  2. 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.
  3. 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.
  4. Implement Authentication and User Management:

    • Set up NextAuth.js for authentication.
    • Create login, registration, and profile pages.
    • Implement role-based access control if needed.
  5. 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>
  );
}

Database Schema

The application uses Cloudflare D1 (SQLite-compatible) for data storage. The database schema is defined in migration files and includes the following tables:

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
);

Simulations Table

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);

Simulations Table

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);

Simulation Users Table

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);

Companies Table

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);

Products Table

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);

Decisions Table

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);

Market Conditions Table

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);

Performance Results Table

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);

Product Performance Table

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);

Events Table

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);

Transactions Table

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);

Research Projects Table

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);

Human Resources Table

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);

Marketing Campaigns Table

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);

Competitor Actions Table

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

Database migrations are managed using Wrangler's D1 migration system. Migrations are stored in the migrations directory and applied using the Wrangler CLI.

Initial Migration

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:

http://localhost:3000/api


## 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
  }
}

Error Response

{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": {
      // Optional additional error details
    }
  }
}

Common Error Codes

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

API Endpoints

Authentication

Register a new user

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"
    }
  }
}

Log in

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 current session

GET /auth/session

Response:

{
  "success": true,
  "data": {
    "user": {
      "id": "user_123",
      "name": "John Doe",
      "email": "[email protected]",
      "role": "user"
    }
  }
}

Log out

GET /auth/logout

Response:

{
  "success": true,
  "data": {
    "message": "Logged out successfully"
  }
}

Simulations

Get all simulations

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
  }
}

Create a new simulation

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 a specific simulation

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
      }
    }
  }
}

Update a simulation

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 a simulation

DELETE /simulations/:id

Path Parameters:

Parameter Type Description
id string Simulation ID

Response:

{
  "success": true,
  "data": {
    "message": "Simulation deleted successfully"
  }
}

Join a simulation

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"
    }
  }
}

Advance to the next period

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...
    }
  }
}

Companies

Get all companies for the current user

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...
    ]
  }
}

Create a new company

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 a specific company

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"
      }
    }
  }
}

Update a company

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 a company

DELETE /companies/:id

Path Parameters:

Parameter Type Description
id string Company ID

Response:

{
  "success": true,
  "data": {
    "message": "Company deleted successfully"
  }
}

Products

Get all products for a company

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...
    ]
  }
}

Create a new product

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 a specific product

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
"""
Business Simulation Market Dynamics
==================================
This module provides market simulation functionality, including market trends,
consumer behavior, and competitive dynamics.
"""
import random
import math
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple
class MarketSimulator:
"""Simulates market dynamics and consumer behavior."""
def __init__(self, config: Dict[str, Any]):
"""
Initialize the market simulator.
Args:
config: Market configuration parameters
"""
self.config = config
self.segments = config.get('segments', ['budget', 'mid-range', 'premium'])
self.total_market_size = config.get('initial_market_size', 1000000)
self.growth_rate = config.get('growth_rate', 0.05)
self.segment_distribution = config.get('segment_distribution',
{'budget': 0.5, 'mid-range': 0.3, 'premium': 0.2})
self.price_sensitivity = config.get('price_sensitivity',
{'budget': 0.8, 'mid-range': 0.5, 'premium': 0.3})
self.quality_sensitivity = config.get('quality_sensitivity',
{'budget': 0.2, 'mid-range': 0.5, 'premium': 0.7})
self.brand_sensitivity = config.get('brand_sensitivity',
{'budget': 0.3, 'mid-range': 0.5, 'premium': 0.7})
self.innovation_sensitivity = config.get('innovation_sensitivity',
{'budget': 0.2, 'mid-range': 0.4, 'premium': 0.6})
self.market_trends = MarketTrends(config.get('trends_config', {}))
self.consumer_behavior = ConsumerBehavior(config.get('consumer_config', {}))
self.competitive_dynamics = CompetitiveDynamics(config.get('competition_config', {}))
def generate_market_conditions(self, period: int) -> Dict[str, Any]:
"""
Generate market conditions for a specific period.
Args:
period: The period number
Returns:
Dict containing market conditions
"""
# Calculate market growth
growth_factor = (1 + self.growth_rate) ** period
current_market_size = self.total_market_size * growth_factor
# Get market trends for this period
trends = self.market_trends.get_trends(period)
# Apply trend effects to market size
trend_growth_factor = 1 + trends.get('market_growth_impact', 0)
current_market_size *= trend_growth_factor
# Apply trend effects to segment distribution
segment_distribution = {}
for segment in self.segments:
base_distribution = self.segment_distribution.get(segment, 1.0 / len(self.segments))
# Apply trend effects
segment_trend_factor = 1 + trends.get('segment_shifts', {}).get(segment, 0)
# Add random variation (±10%)
random_factor = 1 + (random.random() * 0.2 - 0.1)
segment_distribution[segment] = base_distribution * segment_trend_factor * random_factor
# Normalize to ensure sum is 1.0
total = sum(segment_distribution.values())
segment_distribution = {k: v / total for k, v in segment_distribution.items()}
# Calculate segment sizes
segment_sizes = {segment: current_market_size * dist
for segment, dist in segment_distribution.items()}
# Generate consumer preferences
consumer_preferences = self.consumer_behavior.generate_preferences(
self.segments, self.price_sensitivity, self.quality_sensitivity,
self.brand_sensitivity, self.innovation_sensitivity, trends)
# Generate economic indicators
economic_indicators = self._generate_economic_indicators(period, trends)
return {
'period': period,
'timestamp': datetime.now().isoformat(),
'total_market_size': current_market_size,
'segment_distribution': segment_distribution,
'segment_sizes': segment_sizes,
'consumer_preferences': consumer_preferences,
'economic_indicators': economic_indicators,
'market_trends': trends
}
def calculate_market_shares(self, products: List[Dict[str, Any]],
market_conditions: Dict[str, Any]) -> Dict[str, float]:
"""
Calculate market shares for products based on market conditions.
Args:
products: List of products from all companies
market_conditions: Current market conditions
Returns:
Dict mapping product IDs to market share percentages
"""
# Group products by segment
segment_products = {}
for product in products:
segment = product.get('category', 'general')
if segment not in segment_products:
segment_products[segment] = []
segment_products[segment].append(product)
# Calculate attractiveness and market share within each segment
market_shares = {}
for segment, segment_products_list in segment_products.items():
# Get segment-specific consumer preferences
preferences = market_conditions.get('consumer_preferences', {}).get(segment, {})
price_sensitivity = preferences.get('price_sensitivity', 0.5)
quality_sensitivity = preferences.get('quality_sensitivity', 0.5)
brand_sensitivity = preferences.get('brand_loyalty', 0.3)
innovation_sensitivity = preferences.get('innovation_preference', 0.4)
# Calculate attractiveness for each product
product_attractiveness = {}
for product in segment_products_list:
price_score = 1 - (product.get('selling_price', 100) / 200) # Normalize price
quality_score = product.get('quality_rating', 1) / 10 # Normalize quality
brand_score = product.get('brand_rating', 1) / 10 # Normalize brand
innovation_score = product.get('innovation_rating', 1) / 10 # Normalize innovation
# Weight scores by consumer preferences
attractiveness = (
price_score * price_sensitivity +
quality_score * quality_sensitivity +
brand_score * brand_sensitivity +
innovation_score * innovation_sensitivity
)
product_attractiveness[product['id']] = attractiveness
# Calculate market share based on relative attractiveness
total_attractiveness = sum(product_attractiveness.values())
if total_attractiveness > 0:
segment_size = market_conditions.get('segment_sizes', {}).get(segment, 0)
for product_id, attractiveness in product_attractiveness.items():
market_share = attractiveness / total_attractiveness
market_shares[product_id] = {
'segment_share': market_share,
'overall_share': market_share * segment_size / market_conditions.get('total_market_size', 1),
'segment': segment,
'attractiveness': attractiveness
}
return market_shares
def simulate_competitive_response(self, company_actions: Dict[str, List[Dict[str, Any]]],
market_conditions: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
"""
Simulate competitive responses to company actions.
Args:
company_actions: Dictionary mapping company IDs to their actions
market_conditions: Current market conditions
Returns:
Dict mapping company IDs to their competitive responses
"""
return self.competitive_dynamics.generate_responses(company_actions, market_conditions)
def _generate_economic_indicators(self, period: int, trends: Dict[str, Any]) -> Dict[str, float]:
"""
Generate economic indicators for a period.
Args:
period: The period number
trends: Market trends for the period
Returns:
Dict containing economic indicators
"""
# Base economic cycle (simplified)
cycle_length = 12 # periods
cycle_position = period % cycle_length
cycle_factor = math.sin(cycle_position / cycle_length * 2 * math.pi)
# Apply trend effects
economic_trend = trends.get('economic_trend', 0)
# Generate indicators with cyclical patterns and trend effects
gdp_growth = 0.02 + (0.03 * cycle_factor) + economic_trend
inflation_rate = 0.02 + (0.02 * -cycle_factor) + (economic_trend / 2)
unemployment_rate = 0.05 + (0.03 * -cycle_factor) - (economic_trend * 2)
interest_rate = 0.03 + (0.02 * -cycle_factor) + (inflation_rate / 2)
# Add some randomness
gdp_growth += random.uniform(-0.01, 0.01)
inflation_rate += random.uniform(-0.005, 0.005)
unemployment_rate += random.uniform(-0.01, 0.01)
interest_rate += random.uniform(-0.005, 0.005)
# Ensure reasonable bounds
unemployment_rate = max(0.02, min(0.15, unemployment_rate))
inflation_rate = max(0, min(0.15, inflation_rate))
interest_rate = max(0.01, min(0.15, interest_rate))
return {
'gdp_growth': gdp_growth,
'inflation_rate': inflation_rate,
'unemployment_rate': unemployment_rate,
'interest_rate': interest_rate,
'consumer_confidence': 0.5 + (0.3 * cycle_factor) + (economic_trend * 2) + random.uniform(-0.1, 0.1)
}
class MarketTrends:
"""Generates and manages market trends over time."""
def __init__(self, config: Dict[str, Any]):
"""
Initialize market trends.
Args:
config: Trends configuration parameters
"""
self.config = config
self.trend_change_probability = config.get('trend_change_probability', 0.2)
self.trend_strength = config.get('trend_strength', 0.1)
self.current_trends = self._initialize_trends()
self.trend_history = []
def get_trends(self, period: int) -> Dict[str, Any]:
"""
Get market trends for a specific period.
Args:
period: The period number
Returns:
Dict containing market trends
"""
# Update trends if needed
if period >= len(self.trend_history):
self._update_trends(period)
# Return trends for the period
if period < len(self.trend_history):
return self.trend_history[period]
else:
# Fallback to current trends
return self.current_trends
def _initialize_trends(self) -> Dict[str, Any]:
"""
Initialize starting market trends.
Returns:
Dict containing initial trends
"""
return {
'market_growth_impact': 0,
'segment_shifts': {
'budget': 0,
'mid-range': 0,
'premium': 0
},
'consumer_preference_shifts': {
'price_sensitivity': 0,
'quality_sensitivity': 0,
'brand_loyalty': 0,
'innovation_preference': 0
},
'economic_trend': 0,
'technology_trends': [],
'sustainability_importance': 0.3 + random.uniform(-0.1, 0.1)
}
def _update_trends(self, period: int) -> None:
"""
Update market trends for a new period.
Args:
period: The period number
"""
# Ensure trend history is up to date
while len(self.trend_history) < period:
# Copy previous trends or initialize if first period
if self.trend_history:
previous_trends = self.trend_history[-1].copy()
else:
previous_trends = self.current_trends.copy()
# Apply random changes to trends
new_trends = self._evolve_trends(previous_trends)
# Add to history
self.trend_history.append(new_trends)
# Update current trends
self.current_trends = new_trends
def _evolve_trends(self, previous_trends: Dict[str, Any]) -> Dict[str, Any]:
"""
Evolve trends from previous period.
Args:
previous_trends: Trends from previous period
Returns:
Dict containing evolved trends
"""
new_trends = previous_trends.copy()
# Evolve market growth impact
if random.random() < self.trend_change_probability:
# Shift direction
new_trends['market_growth_impact'] += random.uniform(-self.trend_strength, self.trend_strength)
# Limit range
new_trends['market_growth_impact'] = max(-0.2, min(0.2, new_trends['market_growth_impact']))
# Evolve segment shifts
for segment in new_trends['segment_shifts']:
if random.random() < self.trend_change_probability:
new_trends['segment_shifts'][segment] += random.uniform(-self.trend_strength, self.trend_strength)
# Limit range
new_trends['segment_shifts'][segment] = max(-0.3, min(0.3, new_trends['segment_shifts'][segment]))
# Evolve consumer preference shifts
for preference in new_trends['consumer_preference_shifts']:
if random.random() < self.trend_change_probability:
new_trends['consumer_preference_shifts'][preference] += random.uniform(-self.trend_strength/2, self.trend_strength/2)
# Limit range
new_trends['consumer_preference_shifts'][preference] = max(-0.2, min(0.2, new_trends['consumer_preference_shifts'][preference]))
# Evolve economic trend
if random.random() < self.trend_change_probability:
new_trends['economic_trend'] += random.uniform(-self.trend_strength, self.trend_strength)
# Limit range
new_trends['economic_trend'] = max(-0.1, min(0.1, new_trends['economic_trend']))
# Evolve technology trends
if random.random() < self.trend_change_probability:
# Potentially add new technology trend
if random.random() < 0.3 and len(new_trends['technology_trends']) < 3:
new_tech = self._generate_technology_trend()
new_trends['technology_trends'].append(new_tech)
# Potentially remove old technology trend
if random.random() < 0.2 and new_trends['technology_trends']:
new_trends['technology_trends'].pop(0)
# Evolve sustainability importance
if random.random() < self.trend_change_probability:
# Generally increasing over time with some fluctuation
new_trends['sustainability_importance'] += random.uniform(-0.05, 0.1)
# Limit range
new_trends['sustainability_importance'] = max(0.1, min(0.9, new_trends['sustainability_importance']))
return new_trends
def _generate_technology_trend(self) -> Dict[str, Any]:
"""
Generate a new technology trend.
Returns:
Dict containing technology trend details
"""
# Randomly select a technology type
technology_types = ['AI', 'Blockchain', 'Cloud Computing', 'Internet of Things', 'Robotics']
technology_type = random.choice(technology_types)
return {
'type': technology_type,
'impact': random.uniform(-0.1, 0.1),
'trend_duration': random.randint(1, 3) # Number of periods the trend lasts
}
"""
Business Simulation Engine Core
==============================
This module provides the core functionality for the business simulation engine.
It includes classes for managing simulation state, processing decisions, and
calculating outcomes based on business logic.
"""
import json
import random
import math
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple
class SimulationEngine:
"""Main simulation engine that coordinates all simulation components."""
def __init__(self, config: Dict[str, Any]):
"""
Initialize the simulation engine with configuration.
Args:
config: Dictionary containing simulation configuration parameters
"""
self.config = config
self.current_period = 0
self.max_periods = config.get('max_periods', 12)
self.companies = {}
self.market = Market(config.get('market_config', {}))
self.decision_processor = DecisionProcessor()
self.performance_calculator = PerformanceCalculator()
self.event_generator = EventGenerator(config.get('event_config', {}))
self.is_initialized = False
def initialize_simulation(self) -> None:
"""Set up the initial state of the simulation."""
self.current_period = 0
self.is_initialized = True
self.market.initialize_market()
def register_company(self, company_id: str, company_data: Dict[str, Any]) -> None:
"""
Register a company in the simulation.
Args:
company_id: Unique identifier for the company
company_data: Initial company data
"""
self.companies[company_id] = Company(company_id, company_data)
def process_period(self) -> Dict[str, Any]:
"""
Process a complete simulation period.
Returns:
Dict containing the results of the period processing
"""
if not self.is_initialized:
raise RuntimeError("Simulation must be initialized before processing periods")
if self.current_period >= self.max_periods:
return {"status": "completed", "message": "Simulation has reached maximum periods"}
# Generate market conditions for the period
market_conditions = self.market.generate_market_conditions(self.current_period)
# Generate random events for the period
period_events = self.event_generator.generate_events(self.current_period, market_conditions)
# Process decisions for each company
for company_id, company in self.companies.items():
decisions = company.get_pending_decisions()
processed_decisions = self.decision_processor.process_decisions(
decisions,
company,
market_conditions,
period_events
)
company.apply_processed_decisions(processed_decisions)
# Calculate performance for each company
for company_id, company in self.companies.items():
performance = self.performance_calculator.calculate_performance(
company,
market_conditions,
self.companies # Pass all companies for competitive analysis
)
company.update_performance(performance)
# Update market based on company actions
self.market.update_market(self.companies, period_events)
# Advance to next period
self.current_period += 1
return {
"status": "success",
"period": self.current_period - 1,
"market_conditions": market_conditions,
"events": period_events,
"companies": {cid: c.get_public_data() for cid, c in self.companies.items()}
}
def get_simulation_state(self) -> Dict[str, Any]:
"""
Get the current state of the simulation.
Returns:
Dict containing the current simulation state
"""
return {
"current_period": self.current_period,
"max_periods": self.max_periods,
"is_initialized": self.is_initialized,
"market": self.market.get_state(),
"companies": {cid: c.get_state() for cid, c in self.companies.items()},
"config": self.config
}
def load_simulation_state(self, state: Dict[str, Any]) -> None:
"""
Load a simulation state.
Args:
state: Dictionary containing simulation state to load
"""
self.current_period = state.get("current_period", 0)
self.max_periods = state.get("max_periods", 12)
self.is_initialized = state.get("is_initialized", False)
self.config = state.get("config", {})
# Load market state
self.market = Market(self.config.get('market_config', {}))
self.market.load_state(state.get("market", {}))
# Load companies
self.companies = {}
for company_id, company_state in state.get("companies", {}).items():
company = Company(company_id, {})
company.load_state(company_state)
self.companies[company_id] = company
class Company:
"""Represents a company in the simulation."""
def __init__(self, company_id: str, initial_data: Dict[str, Any]):
"""
Initialize a company.
Args:
company_id: Unique identifier for the company
initial_data: Initial company data
"""
self.id = company_id
self.name = initial_data.get('name', f"Company {company_id}")
self.cash = initial_data.get('initial_cash', 1000000.0)
self.products = initial_data.get('products', [])
self.resources = initial_data.get('resources', {})
self.pending_decisions = []
self.decision_history = []
self.performance_history = []
def add_decision(self, decision: Dict[str, Any]) -> None:
"""
Add a pending decision for the company.
Args:
decision: Decision data
"""
decision['timestamp'] = datetime.now().isoformat()
decision['status'] = 'pending'
self.pending_decisions.append(decision)
def get_pending_decisions(self) -> List[Dict[str, Any]]:
"""
Get all pending decisions.
Returns:
List of pending decisions
"""
return self.pending_decisions
def apply_processed_decisions(self, processed_decisions: List[Dict[str, Any]]) -> None:
"""
Apply processed decisions to the company state.
Args:
processed_decisions: List of processed decisions with outcomes
"""
for decision in processed_decisions:
# Update decision status
decision['status'] = 'applied'
# Apply financial impact
if 'financial_impact' in decision:
self.cash += decision['financial_impact']
# Apply product changes
if decision['type'] == 'product_development' and 'product' in decision:
self._update_or_add_product(decision['product'])
# Apply resource changes
if decision['type'] == 'resource_allocation' and 'resources' in decision:
self._update_resources(decision['resources'])
# Add to decision history
self.decision_history.append(decision)
# Clear pending decisions
self.pending_decisions = []
def update_performance(self, performance: Dict[str, Any]) -> None:
"""
Update company performance metrics.
Args:
performance: Dictionary of performance metrics
"""
# Add timestamp
performance['timestamp'] = datetime.now().isoformat()
# Update cash based on profit/loss
if 'profit' in performance:
self.cash += performance['profit']
# Add to performance history
self.performance_history.append(performance)
def get_public_data(self) -> Dict[str, Any]:
"""
Get public-facing company data.
Returns:
Dict containing public company data
"""
# Return subset of data visible to other companies/players
return {
'id': self.id,
'name': self.name,
'products': [self._get_public_product_data(p) for p in self.products],
'market_share': self._calculate_market_share(),
'performance': self._get_latest_performance()
}
def get_state(self) -> Dict[str, Any]:
"""
Get complete company state.
Returns:
Dict containing complete company state
"""
return {
'id': self.id,
'name': self.name,
'cash': self.cash,
'products': self.products,
'resources': self.resources,
'pending_decisions': self.pending_decisions,
'decision_history': self.decision_history,
'performance_history': self.performance_history
}
def load_state(self, state: Dict[str, Any]) -> None:
"""
Load company state.
Args:
state: Dictionary containing company state to load
"""
self.id = state.get('id', self.id)
self.name = state.get('name', self.name)
self.cash = state.get('cash', self.cash)
self.products = state.get('products', self.products)
self.resources = state.get('resources', self.resources)
self.pending_decisions = state.get('pending_decisions', self.pending_decisions)
self.decision_history = state.get('decision_history', self.decision_history)
self.performance_history = state.get('performance_history', self.performance_history)
def _update_or_add_product(self, product: Dict[str, Any]) -> None:
"""
Update existing product or add new product.
Args:
product: Product data
"""
# Check if product already exists
for i, existing_product in enumerate(self.products):
if existing_product['id'] == product['id']:
# Update existing product
self.products[i] = product
return
# Add new product
self.products.append(product)
def _update_resources(self, resources: Dict[str, Any]) -> None:
"""
Update company resources.
Args:
resources: Resource allocation data
"""
for resource_type, allocation in resources.items():
if resource_type in self.resources:
self.resources[resource_type].update(allocation)
else:
self.resources[resource_type] = allocation
def _calculate_market_share(self) -> float:
"""
Calculate company's market share based on latest performance.
Returns:
Float representing market share percentage
"""
if not self.performance_history:
return 0.0
latest_performance = self.performance_history[-1]
return latest_performance.get('market_share', 0.0)
def _get_latest_performance(self) -> Dict[str, Any]:
"""
Get the latest performance metrics.
Returns:
Dict containing latest performance metrics
"""
if not self.performance_history:
return {}
return {k: v for k, v in self.performance_history[-1].items()
if k not in ['timestamp', 'detailed_metrics']}
def _get_public_product_data(self, product: Dict[str, Any]) -> Dict[str, Any]:
"""
Get public-facing product data.
Args:
product: Complete product data
Returns:
Dict containing public product data
"""
return {
'id': product['id'],
'name': product['name'],
'category': product['category'],
'quality_rating': product.get('quality_rating', 0),
'price': product.get('selling_price', 0)
}
class Market:
"""Represents the market environment in the simulation."""
def __init__(self, config: Dict[str, Any]):
"""
Initialize the market.
Args:
config: Market configuration parameters
"""
self.config = config
self.segments = config.get('segments', ['budget', 'mid-range', 'premium'])
self.total_market_size = config.get('initial_market_size', 1000000)
self.growth_rate = config.get('growth_rate', 0.05)
self.segment_distribution = config.get('segment_distribution',
{'budget': 0.5, 'mid-range': 0.3, 'premium': 0.2})
self.price_sensitivity = config.get('price_sensitivity',
{'budget': 0.8, 'mid-range': 0.5, 'premium': 0.3})
self.quality_sensitivity = config.get('quality_sensitivity',
{'budget': 0.2, 'mid-range': 0.5, 'premium': 0.7})
self.conditions_history = []
def initialize_market(self) -> None:
"""Initialize market conditions."""
initial_conditions = self.generate_market_conditions(0)
self.conditions_history.append(initial_conditions)
def generate_market_conditions(self, period: int) -> Dict[str, Any]:
"""
Generate market conditions for a specific period.
Args:
period: The period number
Returns:
Dict containing market conditions
"""
# Calculate market growth
growth_factor = (1 + self.growth_rate) ** period
current_market_size = self.total_market_size * growth_factor
# Add some randomness to segment distribution
segment_distribution = {}
for segment in self.segments:
base_distribution = self.segment_distribution.get(segment, 1.0 / len(self.segments))
# Add up to ±10% random variation
random_factor = 1 + (random.random() * 0.2 - 0.1)
segment_distribution[segment] = base_distribution * random_factor
# Normalize to ensure sum is 1.0
total = sum(segment_distribution.values())
segment_distribution = {k: v / total for k, v in segment_distribution.items()}
# Calculate segment sizes
segment_sizes = {segment: current_market_size * dist
for segment, dist in segment_distribution.items()}
# Generate consumer preferences
consumer_preferences = {}
for segment in self.segments:
consumer_preferences[segment] = {
'price_sensitivity': self.price_sensitivity.get(segment, 0.5),
'quality_sensitivity': self.quality_sensitivity.get(segment, 0.5),
# Add other preferences as needed
'brand_loyalty': random.uniform(0.1, 0.5),
'innovation_preference': random.uniform(0.2, 0.8)
}
# Generate economic indicators
economic_indicators = {
'gdp_growth': random.uniform(-0.02, 0.05),
'inflation_rate': random.uniform(0.01, 0.04),
'unemployment_rate': random.uniform(0.03, 0.08),
'interest_rate': random.uniform(0.02, 0.06)
}
conditions = {
'period': period,
'timestamp': datetime.now().isoformat(),
'market_size': current_market_size,
'segment_sizes': segment_sizes,
'consumer_preferences': consumer_preferences,
'economic_indicators': economic_indicators
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment