Add models, enums, and services for user roles, theme preferences, slug history, and ID generation

This commit is contained in:
pacnpal
2025-02-23 19:50:40 -05:00
parent 32aea21e48
commit 7e5d15eb46
55 changed files with 6462 additions and 4 deletions

View File

@@ -0,0 +1,208 @@
# Area Organization System
## Overview
The Area Organization system provides a flexible way to structure and order areas within a park. It supports both flat and nested hierarchies, with drag-and-drop reordering capabilities and efficient position management.
## Database Structure
### Park Areas Table
```sql
CREATE TABLE park_areas (
id bigint unsigned NOT NULL AUTO_INCREMENT,
park_id bigint unsigned NOT NULL,
parent_id bigint unsigned NULL,
name varchar(255) NOT NULL,
slug varchar(255) NOT NULL,
description text NULL,
opening_date date NULL,
closing_date date NULL,
position integer NOT NULL DEFAULT 0,
created_at timestamp NULL,
updated_at timestamp NULL,
PRIMARY KEY (id),
FOREIGN KEY (park_id) REFERENCES parks(id),
FOREIGN KEY (parent_id) REFERENCES park_areas(id),
INDEX idx_ordering (park_id, position),
INDEX idx_hierarchy (park_id, parent_id)
);
```
## Key Features
### 1. Position Management
- Automatic position assignment for new areas
- Zero-based position indexing
- Position maintenance during reordering
- Efficient batch updates for position changes
### 2. Hierarchical Structure
- Parent-child relationships between areas
- Unlimited nesting depth
- Separate position sequences per parent
- Cascading deletion options
### 3. Query Optimization
- Compound indexes for efficient ordering
- Optimized parent-child lookups
- Position-based sorting
- Scoped uniqueness constraints
## Implementation Details
### Position Management
1. New Area Creation
```php
protected static function boot()
{
parent::boot();
static::creating(function (ParkArea $area) {
if (is_null($area->position)) {
$area->position = $area->getNextPosition();
}
});
}
```
2. Position Calculation
```php
public function getNextPosition(): int
{
$maxPosition = static::where('park_id', $this->park_id)
->where('parent_id', $this->parent_id)
->max('position');
return ($maxPosition ?? -1) + 1;
}
```
3. Position Updates
```php
public function moveToPosition(int $newPosition): void
{
if ($newPosition === $this->position) {
return;
}
$oldPosition = $this->position;
if ($newPosition > $oldPosition) {
// Moving down: decrement positions of items in between
static::where('park_id', $this->park_id)
->where('parent_id', $this->parent_id)
->whereBetween('position', [$oldPosition + 1, $newPosition])
->decrement('position');
} else {
// Moving up: increment positions of items in between
static::where('park_id', $this->park_id)
->where('parent_id', $this->parent_id)
->whereBetween('position', [$newPosition, $oldPosition - 1])
->increment('position');
}
$this->update(['position' => $newPosition]);
}
```
### Hierarchical Relationships
1. Parent Relationship
```php
public function parent(): BelongsTo
{
return $this->belongsTo(ParkArea::class, 'parent_id');
}
```
2. Children Relationship
```php
public function children(): HasMany
{
return $this->hasMany(ParkArea::class, 'parent_id')
->orderBy('position');
}
```
3. Helper Methods
```php
public function hasChildren(): bool
{
return $this->children()->exists();
}
public function isTopLevel(): bool
{
return is_null($this->parent_id);
}
```
## Usage Examples
### Creating a New Area
```php
$area = new ParkArea([
'name' => 'Adventure Zone',
'description' => 'Thrilling rides area',
]);
$park->areas()->save($area);
```
### Moving an Area
```php
$area->moveToPosition(5);
```
### Adding a Sub-Area
```php
$subArea = new ParkArea([
'name' => 'Coaster Corner',
'parent_id' => $area->id,
]);
$park->areas()->save($subArea);
```
## Future Enhancements
1. [ ] Add drag-and-drop reordering UI
2. [ ] Implement position validation
3. [ ] Add move restrictions
4. [ ] Implement area statistics
5. [ ] Add bulk reordering
6. [ ] Implement depth limits
7. [ ] Add position caching
8. [ ] Implement move history
## Security Considerations
1. Position Validation
- Prevent out-of-bounds positions
- Validate parent-child relationships
- Check for circular references
2. Access Control
- Restrict reordering permissions
- Validate park ownership
- Log position changes
## Performance Optimization
1. Batch Updates
- Use transactions for moves
- Minimize position updates
- Cache position values
2. Query Optimization
- Use compound indexes
- Minimize nested queries
- Efficient position calculations
## Testing Strategy
1. Unit Tests
- [ ] Position calculation
- [ ] Move operations
- [ ] Parent-child relationships
2. Integration Tests
- [ ] Reordering flows
- [ ] Nested operations
- [ ] Position maintenance
3. Performance Tests
- [ ] Large-scale reordering
- [ ] Nested structure queries
- [ ] Position update efficiency

View File

@@ -0,0 +1,216 @@
# Area Statistics System
## Overview
The Area Statistics system provides comprehensive tracking and management of various metrics for park areas, including ride counts, visitor statistics, and historical data. This system enables data-driven insights and performance monitoring at both the area and park level.
## Database Structure
### Park Areas Table Statistics Fields
```sql
ALTER TABLE park_areas ADD (
-- Ride statistics
ride_count integer DEFAULT 0,
coaster_count integer DEFAULT 0,
flat_ride_count integer DEFAULT 0,
water_ride_count integer DEFAULT 0,
-- Visitor statistics
daily_capacity integer NULL,
peak_wait_time integer NULL,
average_rating decimal(3,2) NULL,
-- Historical data
total_rides_operated integer DEFAULT 0,
retired_rides_count integer DEFAULT 0,
last_new_ride_added date NULL,
-- Indexes
INDEX idx_rides (park_id, ride_count),
INDEX idx_coasters (park_id, coaster_count),
INDEX idx_rating (park_id, average_rating)
);
```
## Components
### 1. HasAreaStatistics Trait
Located in `app/Traits/HasAreaStatistics.php`
Purpose:
- Provides statistics management functionality
- Handles calculations and formatting
- Manages data updates
- Tracks historical metrics
Features:
1. Ride Statistics
- Total ride count
- Type distribution
- Coaster percentage
- Historical tracking
2. Visitor Metrics
- Daily capacity
- Peak wait times
- Average ratings
- Formatted displays
3. Historical Data
- Total rides operated
- Retirement tracking
- Last addition date
- Retirement rate
## Implementation Details
### Ride Count Management
```php
public function updateRideCounts(array $counts): void
{
$this->update([
'ride_count' => $counts['total'] ?? 0,
'coaster_count' => $counts['coasters'] ?? 0,
'flat_ride_count' => $counts['flat_rides'] ?? 0,
'water_ride_count' => $counts['water_rides'] ?? 0,
]);
}
```
### Visitor Statistics
```php
public function updateVisitorStats(
int $dailyCapacity,
int $peakWaitTime,
float $rating
): void
{
$this->update([
'daily_capacity' => $dailyCapacity,
'peak_wait_time' => $peakWaitTime,
'average_rating' => round($rating, 2),
]);
}
```
### Historical Tracking
```php
public function recordNewRide(): void
{
$this->increment('total_rides_operated');
$this->update(['last_new_ride_added' => now()]);
}
public function recordRetirement(): void
{
$this->increment('retired_rides_count');
}
```
## Display Features
### 1. Rating Display
- Star-based visualization (★★★☆☆)
- Numerical rating with one decimal
- "Not rated" fallback
### 2. Capacity Display
- Formatted numbers with commas
- "riders/day" unit
- Unknown capacity handling
### 3. Wait Time Display
- Minutes format
- Peak time indication
- Unknown time handling
## Data Analysis
### 1. Distribution Analysis
```php
public function getRideDistributionAttribute(): array
{
return [
'coasters' => $this->coaster_count ?? 0,
'flat_rides' => $this->flat_ride_count ?? 0,
'water_rides' => $this->water_ride_count ?? 0,
];
}
```
### 2. Historical Analysis
```php
public function getHistoricalStatsAttribute(): array
{
return [
'total_operated' => $this->total_rides_operated,
'retired_count' => $this->retired_rides_count,
'last_addition' => $this->last_new_ride_added?->format('M Y'),
'retirement_rate' => $this->getRetirementRate(),
];
}
```
## Performance Optimization
### 1. Database Indexes
- Compound indexes for common queries
- Efficient sorting support
- Quick statistical lookups
### 2. Caching Strategy
- [ ] Implement statistics caching
- [ ] Add cache invalidation rules
- [ ] Set up cache warming
## Future Enhancements
1. [ ] Add seasonal statistics
2. [ ] Implement trend analysis
3. [ ] Add capacity forecasting
4. [ ] Create statistical reports
5. [ ] Add comparison tools
6. [ ] Implement benchmarking
7. [ ] Add historical graphs
8. [ ] Create export functionality
## Integration Points
1. Park Model
- Area statistics rollup
- Park-wide metrics
- Comparative analysis
2. Rides System
- Automatic count updates
- Type classification
- Capacity calculation
3. Visitor System
- Wait time tracking
- Rating collection
- Capacity monitoring
## Security Considerations
1. Data Validation
- Range checks
- Type validation
- Update authorization
2. Access Control
- Statistics visibility
- Update permissions
- Export restrictions
## Testing Strategy
1. Unit Tests
- [ ] Calculation accuracy
- [ ] Format handling
- [ ] Edge cases
2. Integration Tests
- [ ] Update operations
- [ ] Rollup functionality
- [ ] Cache invalidation
3. Performance Tests
- [ ] Large dataset handling
- [ ] Update efficiency
- [ ] Query optimization

View File

@@ -0,0 +1,238 @@
# Location System
## Overview
The Location System provides comprehensive location management for parks, areas, and other entities through polymorphic relationships. It includes geocoding, map integration, and location-based search capabilities.
## Components
### 1. Database Structure
#### Locations Table
```sql
CREATE TABLE locations (
id bigint PRIMARY KEY,
locatable_type varchar(255),
locatable_id bigint,
address varchar(255) NULL,
city varchar(255),
state varchar(255) NULL,
country varchar(255),
postal_code varchar(255) NULL,
latitude decimal(10,8),
longitude decimal(11,8),
elevation decimal(8,2) NULL,
timezone varchar(255) NULL,
metadata json NULL,
is_approximate boolean DEFAULT false,
source varchar(255) NULL,
geocoding_data json NULL,
geocoded_at timestamp NULL,
created_at timestamp,
updated_at timestamp,
INDEX idx_coordinates (latitude, longitude),
INDEX idx_location (country, state, city),
INDEX idx_postal (postal_code)
);
```
### 2. Models
#### Location Model
- Polymorphic relationships
- Geocoding integration
- Coordinate handling
- Distance calculations
#### HasLocation Trait
- Location relationship
- Coordinate accessors
- Distance methods
- Map integration
### 3. Services
#### GeocodeService
- Address lookup
- Coordinate validation
- Batch processing
- Cache management
#### LocationSearchService
- Distance-based search
- Boundary queries
- Clustering support
- Performance optimization
### 4. Components
#### LocationSelector
- Map integration
- Address search
- Coordinate picker
- Validation feedback
#### LocationDisplay
- Map rendering
- Marker clustering
- Info windows
- Interactive controls
## Implementation Details
### 1. Model Structure
```php
class Location extends Model
{
protected $fillable = [
'address',
'city',
'state',
'country',
'postal_code',
'latitude',
'longitude',
'elevation',
'timezone',
'metadata',
'is_approximate',
'source',
'geocoding_data',
'geocoded_at',
];
protected $casts = [
'latitude' => 'decimal:8',
'longitude' => 'decimal:8',
'elevation' => 'decimal:2',
'metadata' => 'array',
'geocoding_data' => 'array',
'geocoded_at' => 'datetime',
'is_approximate' => 'boolean',
];
}
```
### 2. Trait Implementation
```php
trait HasLocation
{
public function location()
{
return $this->morphOne(Location::class, 'locatable');
}
public function getCoordinatesAttribute()
{
return [
'lat' => $this->location?->latitude,
'lng' => $this->location?->longitude,
];
}
}
```
## Integration Points
### 1. Parks System
- Location assignment
- Map display
- Area boundaries
- Distance calculations
### 2. Search System
- Location-based filtering
- Distance sorting
- Boundary queries
- Clustering support
### 3. API Integration
- Geocoding services
- Map providers
- Data validation
- Error handling
## Performance Considerations
### 1. Database Design
- Efficient indexes
- Coordinate precision
- Query optimization
- Cache strategy
### 2. Geocoding
- Request limiting
- Cache management
- Batch processing
- Error handling
### 3. Map Integration
- Lazy loading
- Marker clustering
- Viewport management
- Memory optimization
## Future Enhancements
1. [ ] Add route planning
2. [ ] Implement geofencing
3. [ ] Add location sharing
4. [ ] Create heatmaps
5. [ ] Add offline support
6. [ ] Implement navigation
7. [ ] Add location history
8. [ ] Create location alerts
## Security Considerations
### 1. Data Protection
- Coordinate validation
- Input sanitization
- Access control
- Audit logging
### 2. API Security
- Rate limiting
- Token management
- Error handling
- Request validation
## Testing Strategy
### 1. Unit Tests
- [ ] Coordinate validation
- [ ] Distance calculations
- [ ] Geocoding integration
- [ ] Model relationships
### 2. Integration Tests
- [ ] Map integration
- [ ] Search functionality
- [ ] API communication
- [ ] Cache management
### 3. Performance Tests
- [ ] Large datasets
- [ ] Clustering efficiency
- [ ] Query optimization
- [ ] Memory usage
## Monitoring
### 1. Performance Metrics
- [ ] Query timing
- [ ] API response times
- [ ] Cache hit rates
- [ ] Memory usage
### 2. Error Tracking
- [ ] Geocoding failures
- [ ] API errors
- [ ] Invalid coordinates
- [ ] Cache misses
### 3. Usage Analytics
- [ ] Search patterns
- [ ] Popular locations
- [ ] API usage
- [ ] User interactions

View File

@@ -0,0 +1,261 @@
# Parks Management System
## Overview
The Parks Management system provides a comprehensive interface for creating, reading, updating, and deleting theme parks and their areas. It implements a responsive, user-friendly interface while maintaining data integrity and proper relationships.
## Components
### 1. ParkFormComponent
Located in `app/Livewire/ParkFormComponent.php`
Purpose:
- Handles both creation and editing of parks
- Manages form state and validation
- Handles relationships with operators
- Updates statistics automatically
Features:
- Responsive form layout
- Real-time validation
- Status management with enum
- Operator selection
- Date range validation
- Automatic statistics updates
Form Sections:
1. Basic Information
- Park name
- Operator selection
- Description
2. Status and Dates
- Operating status
- Opening/closing dates
3. Additional Details
- Operating season
- Size in acres
- Website
### 2. ParkListComponent
Located in `app/Livewire/ParkListComponent.php`
Purpose:
- Displays paginated list of parks
- Provides filtering and sorting capabilities
- Handles search functionality
- Manages park status display
Features:
1. Search and Filtering
- Text search across name and description
- Status filtering using ParkStatus enum
- Operator filtering
- Multiple sort options
2. Sorting Options
- Name (default)
- Opening Date
- Ride Count
- Coaster Count
- Size
3. Display Features
- Responsive grid layout
- Status badges with colors
- Key statistics display
- Quick access to edit/view
- Website links
- Operator information
### 3. ParkAreaFormComponent
Located in `app/Livewire/ParkAreaFormComponent.php`
Purpose:
- Manages creation and editing of park areas
- Handles area-specific validation
- Maintains park context
- Manages opening/closing dates
Features:
1. Form Organization
- Area basic information section
- Dates management section
- Park context display
- Validation feedback
2. Validation Rules
- Name uniqueness within park
- Date range validation
- Required fields handling
- Custom error messages
3. Data Management
- Park-scoped slugs
- Automatic slug generation
- History tracking
- Date formatting
### 4. ParkAreaListComponent
Located in `app/Livewire/ParkAreaListComponent.php`
Purpose:
- Displays and manages areas within a park
- Provides search and filtering
- Handles area deletion
- Shows operating status
Features:
1. List Management
- Paginated area display
- Search functionality
- Sort by name or date
- Show/hide closed areas
2. Area Display
- Area name and description
- Opening/closing dates
- Operating status
- Quick actions
3. Actions
- Edit area
- Delete area with confirmation
- Add new area
- View area details
4. Filtering Options
- Text search
- Operating status filter
- Sort direction toggle
- Date-based sorting
## UI/UX Design Decisions
### Form Design
1. Sectioned Layout
- Groups related fields together
- Improves visual hierarchy
- Makes long form more manageable
2. Responsive Grid
- Single column on mobile
- Multi-column on larger screens
- Maintains readability at all sizes
3. Validation Feedback
- Immediate error messages
- Clear error states
- Success notifications
### List Design
1. Card Layout
- Visual separation of items
- Key information at a glance
- Status prominence
- Action buttons
2. Filter Controls
- Prominent search
- Quick status filtering
- Flexible sorting
- Toggle controls
## Data Handling
### Validation Rules
```php
// Park Rules
[
'name' => ['required', 'string', 'min:2', 'max:255', 'unique'],
'description' => ['nullable', 'string'],
'status' => ['required', 'enum'],
'opening_date' => ['nullable', 'date'],
'closing_date' => ['nullable', 'date', 'after:opening_date'],
'operating_season' => ['nullable', 'string', 'max:255'],
'size_acres' => ['nullable', 'numeric', 'min:0', 'max:999999.99'],
'website' => ['nullable', 'url', 'max:255'],
'operator_id' => ['nullable', 'exists:operators,id'],
]
// Area Rules
[
'name' => ['required', 'string', 'min:2', 'max:255', 'unique:within_park'],
'description' => ['nullable', 'string'],
'opening_date' => ['nullable', 'date'],
'closing_date' => ['nullable', 'date', 'after:opening_date'],
]
```
### Query Optimization
1. Eager Loading
- Operator relationship
- Areas relationship
- Future: Rides relationship
2. Search Implementation
- Combined name and description search
- Case-insensitive matching
- Proper index usage
3. Filter Efficiency
- Status index
- Operator foreign key index
- Compound sorting
## Future Enhancements
1. [ ] Add image upload support
2. [ ] Implement location selection
3. [ ] Add preview functionality
4. [ ] Add duplicate detection
5. [ ] Implement draft saving
6. [ ] Add bulk operations
7. [ ] Add import/export functionality
8. [ ] Add map view option
9. [ ] Implement advanced search
10. [ ] Add comparison feature
11. [ ] Add area reordering
12. [ ] Implement area statistics
13. [ ] Add drag-and-drop sorting
14. [ ] Implement nested areas
## Integration Points
1. Operators
- Selection in form
- Statistics updates
- Relationship maintenance
2. Slug History
- Automatic slug generation
- Historical slug tracking
- SEO-friendly URLs
3. Park Areas
- Nested management
- Area organization
- Statistics rollup
## Security Considerations
1. Authorization
- [ ] Implement role-based access
- [ ] Add ownership checks
- [ ] Audit logging
2. Validation
- Input sanitization
- CSRF protection
- Rate limiting
## Testing Strategy
1. Unit Tests
- [ ] Validation rules
- [ ] Status transitions
- [ ] Statistics updates
2. Integration Tests
- [ ] Form submission
- [ ] Relationship updates
- [ ] Slug generation
3. Feature Tests
- [ ] Complete CRUD flow
- [ ] Authorization rules
- [ ] Edge cases

View File

@@ -0,0 +1,100 @@
# Slug History System
## Overview
The slug history system provides a way to track changes to model slugs over time, ensuring that old URLs continue to work even after slugs are updated. This is particularly important for maintaining SEO value and preventing broken links.
## Components
### 1. HasSlugHistory Trait
Located in `app/Traits/HasSlugHistory.php`
Key Features:
- Automatic slug generation from name field
- Tracking of slug changes
- Historical slug lookup
- Handling of duplicate slugs
- Polymorphic relationship with SlugHistory model
### 2. SlugHistory Model
Located in `app/Models/SlugHistory.php`
Purpose:
- Stores historical slugs for any model using HasSlugHistory trait
- Uses polymorphic relationships to link with parent models
- Maintains timestamps for tracking when slugs were used
## Database Structure
```sql
CREATE TABLE slug_histories (
id bigint unsigned NOT NULL AUTO_INCREMENT,
sluggable_type varchar(255) NOT NULL,
sluggable_id bigint unsigned NOT NULL,
slug varchar(255) NOT NULL,
created_at timestamp NULL DEFAULT NULL,
updated_at timestamp NULL DEFAULT NULL,
PRIMARY KEY (id),
KEY idx_sluggable (sluggable_type, slug)
);
```
## Usage Example
```php
class Operator extends Model
{
use HasSlugHistory;
// Model implementation
}
// Finding by current or historical slug
$operator = Operator::findBySlug('old-slug');
$operator = Operator::findBySlugOrFail('old-slug');
```
## Current Implementation
Models using the system:
- Operator (park operators)
- Manufacturer (ride manufacturers)
- Park (to be implemented)
- ParkArea (to be implemented)
## Features
1. Automatic Slug Generation
- Converts name to URL-friendly format
- Handles duplicates by appending numbers
- Triggered on model creation
2. History Tracking
- Saves old slugs when updated
- Maintains chronological order
- Links to original model via polymorphic relationship
3. Slug Lookup
- Checks current slugs first
- Falls back to historical slugs
- Maintains efficient indexes for quick lookups
## Benefits
1. SEO Friendly
- Maintains link equity
- Prevents 404 errors
- Supports URL structure changes
2. User Experience
- Old bookmarks continue to work
- Prevents broken links
- Transparent to end users
3. Performance
- Efficient database indexing
- Minimal overhead
- Cached lookups (to be implemented)
## Future Enhancements
1. [ ] Add caching layer for frequent lookups
2. [ ] Implement automatic redirects with proper status codes
3. [ ] Add slug cleanup for old, unused slugs
4. [ ] Add analytics for tracking slug usage

View File

@@ -0,0 +1,230 @@
# Statistics Caching System
## Overview
The Statistics Caching system provides efficient caching and retrieval of statistics across all levels of the theme park hierarchy. It implements a robust caching strategy with automatic invalidation, cache warming, and performance monitoring.
## Components
### 1. Cache Structure
#### Key Prefixes
```php
protected const AREA_PREFIX = 'stats:area:';
protected const PARK_PREFIX = 'stats:park:';
protected const OPERATOR_PREFIX = 'stats:operator:';
```
#### Cache TTL
```php
protected const CACHE_TTL = 86400; // 24 hours
```
### 2. StatisticsCacheService
Located in `app/Services/StatisticsCacheService.php`
Purpose:
- Manage statistics caching
- Handle cache invalidation
- Provide cache warming
- Monitor cache performance
Features:
1. Caching Operations
- Area statistics
- Park rollups
- Operator aggregates
- Batch processing
2. Cache Management
- Automatic invalidation
- Selective updates
- Cache warming
- Error handling
## Implementation Details
### Area Statistics Cache
```php
[
'ride_distribution' => [
'coasters' => 5,
'flat_rides' => 12,
'water_rides' => 3,
],
'daily_capacity' => '25,000 riders/day',
'rating' => '★★★★☆ (4.2)',
'wait_time' => '45 minutes',
'historical' => [
'total_operated' => 25,
'retired_count' => 5,
'last_addition' => 'Mar 2024',
],
'updated_at' => '2024-02-23 19:30:00',
]
```
### Park Statistics Cache
```php
[
'area_distribution' => [
'total' => 8,
'operating' => 7,
'closed' => 1,
],
'ride_distribution' => [
'coasters' => 12,
'flat_rides' => 35,
'water_rides' => 8,
],
'daily_capacity' => '75,000 riders/day',
'rating' => '★★★★★ (4.8)',
'wait_time' => '35 minutes',
'historical' => [...],
'performance' => [
'utilization' => '85%',
'peak_attendance' => '65,000',
'satisfaction' => '4.5/5.0',
],
'updated_at' => '2024-02-23 19:30:00',
]
```
### Operator Statistics Cache
```php
[
'park_count' => 5,
'operating_parks' => 4,
'closed_parks' => 1,
'total_rides' => 275,
'total_coasters' => 45,
'average_rating' => 4.6,
'total_capacity' => 350000,
'updated_at' => '2024-02-23 19:30:00',
]
```
## Cache Management
### 1. Invalidation Strategy
- Automatic invalidation on updates
- Cascading invalidation
- Selective cache clearing
- Error handling
### 2. Cache Warming
```php
public function warmCaches(): void
{
// Process areas in chunks
ParkArea::chunk(100, function ($areas) {
foreach ($areas as $area) {
$this->cacheAreaStatistics($area);
}
});
// Process parks in chunks
Park::chunk(100, function ($parks) {...});
// Process operators in chunks
Operator::chunk(100, function ($operators) {...});
}
```
### 3. Error Handling
```php
try {
Cache::put($key, $data, static::CACHE_TTL);
Log::info("Cached statistics for {$type} {$id}");
} catch (\Exception $e) {
Log::error("Failed to cache statistics: {$e->getMessage()}");
}
```
## Performance Optimization
### 1. Cache Design
- Efficient key structure
- Optimized data format
- Minimal cache churn
- Batch operations
### 2. Memory Usage
- Compact data storage
- Selective caching
- TTL management
- Cache size monitoring
### 3. Invalidation Rules
- Smart invalidation
- Dependency tracking
- Cascade control
- Version management
## Future Enhancements
1. [ ] Add Redis support
2. [ ] Implement cache tags
3. [ ] Add cache versioning
4. [ ] Create cache analytics
5. [ ] Add cache preloading
6. [ ] Implement cache pruning
7. [ ] Add cache monitoring
8. [ ] Create cache dashboard
## Integration Points
1. Statistics System
- Data aggregation
- Cache updates
- Performance metrics
2. Event System
- Cache invalidation
- Update triggers
- Error handling
3. Monitoring System
- Cache hit rates
- Performance tracking
- Error logging
## Security Considerations
1. Data Protection
- Cache encryption
- Access control
- Data validation
2. Error Handling
- Graceful degradation
- Fallback mechanisms
- Error logging
## Testing Strategy
1. Unit Tests
- [ ] Cache operations
- [ ] Invalidation rules
- [ ] Error handling
2. Integration Tests
- [ ] Cache warming
- [ ] Update propagation
- [ ] Performance tests
3. Load Tests
- [ ] Cache hit rates
- [ ] Memory usage
- [ ] Concurrent access
## Monitoring
1. Performance Metrics
- [ ] Cache hit rates
- [ ] Response times
- [ ] Memory usage
2. Error Tracking
- [ ] Failed operations
- [ ] Invalid data
- [ ] System alerts
3. Usage Analytics
- [ ] Access patterns
- [ ] Data freshness
- [ ] Cache efficiency

View File

@@ -0,0 +1,226 @@
# Statistics Rollup System
## Overview
The Statistics Rollup system provides comprehensive tracking and aggregation of statistics across different levels of the theme park hierarchy: areas, parks, and operators. It ensures data consistency and provides real-time insights through automatic updates and scheduled refreshes.
## Components
### 1. Database Structure
#### Park Areas Table Statistics
```sql
ALTER TABLE park_areas ADD (
ride_count integer DEFAULT 0,
coaster_count integer DEFAULT 0,
flat_ride_count integer DEFAULT 0,
water_ride_count integer DEFAULT 0,
daily_capacity integer NULL,
peak_wait_time integer NULL,
average_rating decimal(3,2) NULL,
total_rides_operated integer DEFAULT 0,
retired_rides_count integer DEFAULT 0,
last_new_ride_added date NULL
);
```
#### Parks Table Statistics
```sql
ALTER TABLE parks ADD (
total_areas integer DEFAULT 0,
operating_areas integer DEFAULT 0,
closed_areas integer DEFAULT 0,
total_rides integer DEFAULT 0,
total_coasters integer DEFAULT 0,
total_flat_rides integer DEFAULT 0,
total_water_rides integer DEFAULT 0,
total_daily_capacity integer DEFAULT 0,
average_wait_time integer NULL,
average_rating decimal(3,2) NULL,
total_rides_operated integer DEFAULT 0,
total_rides_retired integer DEFAULT 0,
last_expansion_date date NULL,
last_major_update date NULL,
utilization_rate decimal(5,2) NULL,
peak_daily_attendance integer NULL,
guest_satisfaction decimal(3,2) NULL
);
```
### 2. Traits
#### HasAreaStatistics
Located in `app/Traits/HasAreaStatistics.php`
- Ride count management
- Visitor statistics
- Historical tracking
- Formatted displays
#### HasParkStatistics
Located in `app/Traits/HasParkStatistics.php`
- Area statistics rollup
- Ride statistics aggregation
- Performance metrics
- Historical data tracking
### 3. StatisticsRollupService
Located in `app/Services/StatisticsRollupService.php`
Purpose:
- Coordinate statistics updates
- Maintain data consistency
- Handle events
- Schedule refreshes
Features:
1. Hierarchical Updates
- Bottom-up propagation
- Transaction safety
- Batch processing
- Event handling
2. Update Types
- Area statistics
- Park rollups
- Operator aggregates
- System-wide refresh
## Implementation Details
### Update Flow
1. Area Update
```php
public function updateAreaStatistics(ParkArea $area): void
{
DB::transaction(function () use ($area) {
$this->updateParkStatistics($area->park);
});
}
```
2. Park Rollup
```php
public function updateParkStatistics(Park $park): void
{
DB::transaction(function () use ($park) {
$park->updateAreaCounts();
$park->updateRideStatistics();
$park->updateVisitorStats();
// Update operator if exists
});
}
```
3. Operator Aggregation
```php
public function updateOperatorStatistics(Operator $operator): void
{
DB::transaction(function () use ($operator) {
// Update park counts
// Update ride totals
// Update performance metrics
});
}
```
## Event Handling
### 1. Ride Events
- Addition tracking
- Retirement processing
- Statistics updates
### 2. Park Events
- Expansion recording
- Major updates
- Performance tracking
### 3. Area Events
- Opening/closing
- Status changes
- Capacity updates
## Performance Optimization
### 1. Database Design
- Efficient indexes
- Compound keys
- Query optimization
### 2. Processing Strategy
- Batch updates
- Chunked processing
- Transaction management
### 3. Caching
- [ ] Implement statistics caching
- [ ] Add cache invalidation
- [ ] Set up cache warming
## Future Enhancements
1. [ ] Add trend analysis
2. [ ] Implement forecasting
3. [ ] Add historical graphs
4. [ ] Create export tools
5. [ ] Add benchmarking
6. [ ] Implement alerts
7. [ ] Add reporting
8. [ ] Create dashboards
## Integration Points
1. Areas System
- Statistics collection
- Event handling
- Data validation
2. Parks System
- Rollup processing
- Performance tracking
- Historical data
3. Operators System
- Aggregation logic
- Performance metrics
- Trend analysis
## Security Considerations
1. Data Validation
- Range checks
- Type validation
- Relationship verification
2. Access Control
- Update permissions
- View restrictions
- Audit logging
## Testing Strategy
1. Unit Tests
- [ ] Calculation accuracy
- [ ] Event handling
- [ ] Data validation
2. Integration Tests
- [ ] Update propagation
- [ ] Transaction handling
- [ ] Event processing
3. Performance Tests
- [ ] Large dataset handling
- [ ] Concurrent updates
- [ ] Batch processing
## Monitoring
1. Performance Metrics
- [ ] Update timing
- [ ] Query performance
- [ ] Cache hit rates
2. Error Tracking
- [ ] Failed updates
- [ ] Data inconsistencies
- [ ] System alerts
3. Usage Analytics
- [ ] Update frequency
- [ ] Data access patterns
- [ ] User interactions