Files
motovaultpro/docs/architecture.md
Eric Gullickson f7eca4bad5 first commit
2025-07-15 20:34:05 -05:00

351 lines
13 KiB
Markdown

# MotoVaultPro Architecture Documentation
## Table of Contents
1. [Overview](#overview)
2. [Technology Stack](#technology-stack)
3. [Architecture Patterns](#architecture-patterns)
4. [Project Structure](#project-structure)
5. [Data Layer](#data-layer)
6. [Business Logic Layer](#business-logic-layer)
7. [Controller Layer](#controller-layer)
8. [Frontend Architecture](#frontend-architecture)
9. [Authentication & Security](#authentication--security)
10. [Deployment & Configuration](#deployment--configuration)
11. [API Design](#api-design)
12. [Performance Considerations](#performance-considerations)
13. [Development Guidelines](#development-guidelines)
14. [Future Enhancements](#future-enhancements)
## Overview
MotoVaultPro is a self-hosted, open-source vehicle maintenance and fuel mileage tracking application built with ASP.NET Core 8.0. The application follows a traditional Model-View-Controller (MVC) architecture with modern patterns including dependency injection, repository pattern, and dual-database support.
### Key Features
- Vehicle maintenance tracking and reminders
- Fuel efficiency monitoring and analysis
- Multi-user support with role-based access control
- Dual database support (LiteDB and PostgreSQL)
- RESTful API endpoints
- Progressive Web App (PWA) capabilities
- Internationalization support
- OpenID Connect integration
- File attachment and document management
## Technology Stack
### Core Framework
- **ASP.NET Core 8.0** - Web application framework
- **C# 12** - Programming language
- **Razor Pages** - Server-side rendering engine
### Database Support
- **LiteDB 5.0.17** - Embedded NoSQL database (default)
- **PostgreSQL** - External relational database (via Npgsql 9.0.3)
### Frontend Technologies
- **Bootstrap 5** - UI framework and responsive design
- **jQuery** - DOM manipulation and AJAX
- **Chart.js** - Data visualization
- **SweetAlert2** - Modal dialogs and notifications
### Additional Libraries
- **MailKit 4.11.0** - Email functionality
- **CsvHelper 33.0.1** - CSV import/export
- **System.IdentityModel.Tokens.Jwt 7.3.1** - JWT authentication
- **Bootstrap Extensions** - Date pickers, tag inputs, etc.
## Architecture Patterns
### 1. Model-View-Controller (MVC)
Clean separation of concerns with:
- **Models**: Data representation and business logic
- **Views**: User interface and presentation
- **Controllers**: Request handling and application flow
### 2. Repository Pattern
Data access abstraction through interfaces:
- Interface contracts in `External/Interfaces/`
- Dual implementations for LiteDB and PostgreSQL
- Dependency injection for provider selection
### 3. Dependency Injection
Comprehensive DI container usage:
- Service registration in `Program.cs`
- Constructor injection throughout application
- Singleton lifetime for most services
### 4. Generic Record Pattern
Base class inheritance for consistency:
- `GenericRecord` base class with common properties
- Specialized record types for different data types
- Promotes code reuse and maintainability
### 5. Helper/Service Layer Pattern
Business logic separation:
- Helper classes for specific functionality
- Service classes for complex operations
- Clear separation from controllers
## Project Structure
```
MotoVaultPro/
├── Controllers/ # MVC Controllers
│ ├── Vehicle/ # Vehicle-specific controllers
│ ├── HomeController.cs
│ ├── LoginController.cs
│ └── AdminController.cs
├── Models/ # Data models and ViewModels
│ ├── API/ # API-specific models
│ ├── Shared/ # Common models
│ └── Vehicle/ # Vehicle-related models
├── Views/ # Razor views
│ ├── Shared/ # Common layouts and partials
│ └── Vehicle/ # Vehicle-specific views
├── External/ # Data access layer
│ ├── Interfaces/ # Repository interfaces
│ └── Implementations/ # Database implementations
├── Logic/ # Business logic classes
├── Helper/ # Utility classes
├── Middleware/ # Custom middleware
├── wwwroot/ # Static web assets
└── docs/ # Documentation
```
## Data Layer
### Database Architecture
The application supports dual database backends through a unified repository pattern:
#### LiteDB Implementation
- **File-based storage**: Single database file (`data/cartracker.db`)
- **NoSQL document storage**: Entities stored as JSON documents
- **Embedded database**: No external dependencies
- **Performance**: Excellent for single-user scenarios
#### PostgreSQL Implementation
- **Relational database**: External PostgreSQL server
- **Hybrid schema**: Combines relational structure with JSONB flexibility
- **Scalability**: Supports multi-user scenarios with better performance
- **Advanced features**: Full-text search, complex queries, transactions
### Entity Model
```
Vehicle (Root Entity)
├── ServiceRecord (maintenance and repairs)
├── GasRecord (fuel tracking)
├── CollisionRecord (accident records)
├── UpgradeRecord (modifications)
├── TaxRecord (registration and taxes)
├── SupplyRecord (parts and supplies)
├── PlanRecord (maintenance planning)
├── OdometerRecord (mileage tracking)
├── ReminderRecord (maintenance reminders)
└── Note (general notes)
```
### Data Access Interfaces
Each entity type has a dedicated interface:
- `IVehicleDataAccess` - Vehicle management
- `IServiceRecordDataAccess` - Service records
- `IGasRecordDataAccess` - Fuel tracking
- `IUserRecordDataAccess` - User management
- And more...
## Business Logic Layer
### Logic Classes
- **VehicleLogic**: Core vehicle operations and aggregations
- **UserLogic**: User management and access control
- **LoginLogic**: Authentication and user registration
- **OdometerLogic**: Mileage tracking and validation
### Helper Classes
- **ReminderHelper**: Reminder calculations and urgency
- **ReportHelper**: Data aggregation and reporting
- **StaticHelper**: Common utilities and constants
- **TranslationHelper**: Internationalization support
- **ConfigHelper**: Configuration management
### Business Rules
- **Mileage Progression**: Automatic odometer record management
- **Reminder Urgency**: Complex urgency calculations based on date/mileage
- **Access Control**: Vehicle-level permissions with collaborator system
- **Data Validation**: Input validation and business rule enforcement
## Controller Layer
### Main Controllers
- **HomeController**: Dashboard, settings, and kiosk mode
- **VehicleController**: Vehicle management hub (partial class)
- **LoginController**: Authentication and user management
- **AdminController**: Administrative functions
- **APIController**: RESTful API endpoints
### Vehicle Controller Architecture
The `VehicleController` uses a partial class pattern with specialized controllers:
- **GasController**: Fuel record management
- **ServiceController**: Service record operations
- **ReminderController**: Reminder management
- **ImportController**: CSV import/export
- And more...
### Security and Authorization
- **Authentication Middleware**: Custom authentication handler
- **Role-based Authorization**: Admin, root user, and regular user roles
- **Vehicle-level Permissions**: CollaboratorFilter for fine-grained access
- **API Authentication**: Supports both cookie and Basic Auth
## Frontend Architecture
### View Organization
- **Razor Views**: Server-side rendered with strong typing
- **Partial Views**: Modular components for reusability
- **Layout System**: Single layout with sections for customization
- **Modal-heavy UI**: Extensive use of Bootstrap modals
### JavaScript Architecture
- **jQuery-based**: DOM manipulation and AJAX requests
- **Feature-specific files**: Organized by functionality
- **Global functions**: Accessible throughout the application
- **Event-driven**: Extensive event handling for user interactions
### Styling Approach
- **Bootstrap 5**: Primary CSS framework
- **Custom CSS**: Application-specific styling in `site.css`
- **Responsive Design**: Mobile-first approach with media queries
- **Dark Mode Support**: CSS variables for theme switching
### Progressive Web App (PWA)
- **Web App Manifest**: Proper configuration for app installation
- **Service Worker Ready**: Architecture supports offline functionality
- **Multiple Icons**: Various sizes for different devices
- **Responsive Design**: Optimized for mobile and desktop
## Authentication & Security
### Authentication Modes
- **Cookie-based**: Encrypted session cookies for web interface
- **Basic Authentication**: HTTP Basic Auth for API access
- **OpenID Connect**: External provider integration
- **Token-based**: Registration and password reset tokens
### Authorization Levels
- **Root User**: Full system access (user ID -1)
- **Admin User**: Administrative privileges
- **Regular User**: Standard application access
- **Vehicle Collaborators**: Vehicle-specific permissions
### Security Features
- **Password Hashing**: SHA256 with UTF-8 encoding
- **Data Protection**: ASP.NET Core encryption for cookies
- **PKCE Support**: Enhanced OIDC security
- **File Security**: Authenticated file access and uploads
- **SQL Injection Protection**: Parameterized queries throughout
## Deployment & Configuration
### Database Selection
Configuration-driven database selection:
```csharp
if (!string.IsNullOrWhiteSpace(builder.Configuration["POSTGRES_CONNECTION"]))
{
// Use PostgreSQL
}
else
{
// Use LiteDB (default)
}
```
### Configuration Management
- **Environment Variables**: Database connections and external services
- **JSON Configuration**: Application settings and user preferences
- **Feature Flags**: Enable/disable authentication and features
- **Multi-environment**: Development, staging, production configurations
### Docker Support
- **Multi-stage build**: Optimized Docker image creation
- **ASP.NET Core 8.0 runtime**: Lightweight production image
- **Port 8080**: Standard web application port
- **Volume mounting**: Persistent data storage
## API Design
### RESTful Endpoints
- **Conventional routing**: `/api/{controller}/{action}`
- **JSON responses**: Consistent response format
- **HTTP status codes**: Proper error handling
- **Authentication required**: All endpoints require authentication
### API Features
- **Vehicle data**: CRUD operations for all record types
- **User management**: Authentication and authorization
- **File operations**: Upload and download capabilities
- **Reporting**: Data aggregation and analysis endpoints
## Performance Considerations
### Database Performance
- **Connection pooling**: Efficient connection management (PostgreSQL)
- **Lazy loading**: On-demand data retrieval
- **Caching**: Configuration and translation caching
- **Batch operations**: Efficient bulk data operations
### Frontend Performance
- **Partial views**: Reduced page load times
- **AJAX updates**: Dynamic content without full page reloads
- **Responsive images**: Optimized for different screen sizes
- **Minification ready**: Architecture supports asset bundling
## Development Guidelines
### Code Organization
- **Separation of concerns**: Clear layer boundaries
- **Consistent naming**: Descriptive class and method names
- **Interface-based design**: Abstraction for testability
- **Dependency injection**: Loose coupling between components
### Best Practices
- **Error handling**: Comprehensive exception management
- **Logging**: Structured logging throughout application
- **Validation**: Input validation at multiple layers
- **Security**: Security-first approach to all features
### Testing Strategy
- **Unit testing**: Business logic and data access layers
- **Integration testing**: API endpoints and workflows
- **UI testing**: Frontend functionality and user flows
- **Security testing**: Authentication and authorization
## Future Enhancements
### Scalability Improvements
- **Microservices**: Potential service decomposition
- **Caching layer**: Redis or in-memory caching
- **Load balancing**: Multi-instance deployment support
- **Database sharding**: Data partitioning for scale
### Technology Upgrades
- **Modern JavaScript**: ES6+ modules and TypeScript
- **Frontend framework**: React, Vue, or Angular integration
- **Real-time features**: SignalR for live updates
- **API versioning**: Structured API evolution
### Feature Enhancements
- **Mobile applications**: Native iOS and Android apps
- **Advanced reporting**: Business intelligence features
- **Integration APIs**: Third-party service connections
- **Automated backups**: Scheduled data protection
### Security Enhancements
- **Multi-factor authentication**: Enhanced security options
- **OAuth 2.0**: Extended authentication provider support
- **API rate limiting**: Protection against abuse
- **Audit logging**: Comprehensive security tracking
---
**Last Updated**: January 2025
**Version**: 1.0
**Maintainer**: MotoVaultPro Development Team