Core Features Documentation
Account Managementβ
Overviewβ
The Account Management system provides comprehensive user authentication and profile management capabilities for the multi-tenant SaaS platform. It handles user authentication, profile management, and security features across both trucking and service industry applications.
Endpointsβ
| Method | Endpoint | Description | Authentication Required |
|---|---|---|---|
| POST | /api/v1/account/login | User authentication | No |
| POST | /api/v1/account/logout | Session termination | Yes |
| GET | /api/v1/account/current | Get current user info | Yes |
| POST | /api/v1/account/forgot/password | Password recovery | No |
| PUT | /api/v1/account/update | Update user profile | Yes |
| PUT | /api/v1/account/activate | Account activation | Yes |
| PUT | /api/v1/account/verify/token | Token verification | Yes |
| POST | /api/v1/account/change/password | Password change | Yes |
| POST | /api/v1/account/refresh | Token refresh | No |
Implementation Detailsβ
Security Featuresβ
- JWT-based authentication
- Secure password hashing
- Token-based session management
- Protected routes using middleware
- Secure password reset workflow
User Managementβ
- Complete user lifecycle management
- Profile updates and customization
- Automatic avatar generation
- Email integration for notifications
- Session tracking and management
Integration Pointsβ
- Email service for password recovery and notifications
- Avatar generation service for user profiles
- Frontend URL builder for client redirects
- Token management for session control
Dependenciesβ
Modelsβ
User: Core user data modelToken: Session and authentication token management
Servicesβ
- Email/Mailer service for notifications
- Avatar generation service
- URL building utility
Constantsβ
- Error messages
- Status codes
- General configurations
Best Practicesβ
- All passwords are hashed before storage
- Tokens are validated on protected routes
- Email notifications for security-related actions
- Session management for multi-device support
- Secure password reset flow with tokenization
Industry-Specific Considerationsβ
Trucking Industryβ
- User roles specific to fleet management
- Session management for mobile access
- Location-based authentication considerations
Service Industryβ
- Role-based access for service technicians
- Customer-facing profile management
- Service area-specific configurations
Error Handlingβ
- Comprehensive error messages
- Status code standardization
- User-friendly error responses
- Secure error logging
Future Enhancementsβ
- Two-factor authentication support
- OAuth integration
- Enhanced session analytics
- Role-based access control improvements
- Advanced security logging
Users Managementβ
Overviewβ
The Users Management system provides administrative capabilities for managing users within the multi-tenant platform. It includes features for creating, updating, and managing users with different roles and permissions across both trucking and service industry applications.
Endpointsβ
| Method | Endpoint | Description | Authentication Required |
|---|---|---|---|
| POST | /api/v1/users | Create new user | Yes + Admin |
| GET | /api/v1/users | List all users (paginated) | Yes + Admin |
| GET | /api/v1/users/:id | Get user by ID | Yes + Admin |
| PUT | /api/v1/users/:id | Update user | Yes + Admin |
| DELETE | /api/v1/users/:id | Delete user | Yes + Admin |
| DELETE | /api/v1/users | Bulk delete users | Yes + Admin |
| POST | /api/v1/users/email/:id | Send email to user | Yes + Admin |
Implementation Detailsβ
Security Featuresβ
- Role-based access control (Admin, SuperAdmin)
- Parent company verification
- Pagination for large datasets
- Protected routes with multiple middleware layers
Administrative Capabilitiesβ
- User creation and management
- Bulk operations support
- Email communication
- Role assignment
- Parent company association
Integration Pointsβ
- Email service for user communications
- Authentication system
- Parent company verification
- Pagination service
Dependenciesβ
Modelsβ
User: Core user data model- Organization/Company models for hierarchy
Middlewareβ
verifyToken: Authentication verificationadmin: Role verificationverifyParent: Parent company verificationsuperAdmin: Super admin verificationpaginationHandler: Pagination processing
Servicesβ
- Email/Mailer service
- User management utilities
- Pagination utilities
Best Practicesβ
- Always verify user permissions before operations
- Implement pagination for list operations
- Validate parent company relationships
- Maintain audit trail of user changes
- Handle bulk operations efficiently
Industry-Specific Considerationsβ
Trucking Industryβ
- Driver-specific user roles
- Fleet management hierarchies
- Location-based user management
- Mobile access considerations
Service Industryβ
- Technician-specific user roles
- Service area management
- Customer service roles
- Field service considerations
Error Handlingβ
- Permission-based error responses
- Data validation errors
- Duplicate user handling
- Hierarchical relationship validation
Future Enhancementsβ
- Advanced role management
- User activity tracking
- Enhanced bulk operations
- Improved audit logging
- Advanced search capabilities
Customer (Tenant) Managementβ
Overviewβ
The Customer model serves as the core tenant system in this multi-tenant SaaS platform. Each customer represents a distinct business entity with its own users, configurations, and industry-specific settings. The system supports both trucking and service/repair industries with customizable features for each.
Model Structureβ
CustomerSchema = {
// Core Business Identity
name: { type: String, required: true },
email: { type: String, unique: true, required: true },
slug: { type: String, unique: true, required: true },
logo: String,
// Industry Configuration
industry: { type: String },
appType: { type: String, enum: ["trucking", "serviceRepair"] },
// Business Details
active: Boolean,
phone: String,
address: { type: ObjectId, ref: "Address" },
// Tenant Configuration
metadata: Schema.Types.Mixed,
paymentStatus: { type: String, default: "pending" },
// Relationships
contacts: [{ type: ObjectId, ref: "User" }],
// Timestamps
dateCreated: Date,
dateUpdated: Date,
};
Key Featuresβ
Multi-Industry Supportβ
- Specialized handling for trucking industry
- Customized features for service/repair businesses (Plumbing, HVAC, Electrical)
- Industry-specific configurations and workflows
Tenant Isolationβ
- Separate data spaces for each customer
- Industry-specific feature flags
- Custom metadata support
- Unique slug for routing and identification
Business Managementβ
- Contact management
- Address tracking
- Logo and branding
- Payment status tracking
Implementation Detailsβ
Security Featuresβ
- Tenant isolation at the database level
- Industry-specific access controls
- Payment status-based feature access
- Unique slug validation
Integration Pointsβ
- Address service integration
- User management system
- Payment processing system
- Configuration management
Best Practicesβ
-
Tenant Isolation
- Always scope queries by customer/parentCompany
- Validate cross-tenant data access
- Maintain separate configurations
-
Industry Specifics
- Use appType for feature toggling
- Implement industry-specific validations
- Maintain separate business logic where needed
-
Data Management
- Use metadata for flexible extensions
- Maintain referential integrity with contacts
- Regular validation of required fields
Industry-Specific Implementationsβ
Trucking Industryβ
- Fleet management capabilities
- Route optimization features
- Driver management integration
- Load tracking systems
Service/Repair Industryβ
- Service area management
- Technician scheduling
- Customer service tracking
- Job/Work order management
Error Handlingβ
- Duplicate email/slug detection
- Industry-specific validation errors
- Payment status notifications
- Contact management validation
Future Enhancementsβ
- Enhanced metadata schema validation
- Advanced industry-specific configurations
- Improved tenant isolation patterns
- Extended business type support
- Advanced tenant analytics
Jobs Managementβ
Overviewβ
The Jobs system is a sophisticated feature that handles work orders, service requests, and transportation tasks across both trucking and service/repair industries. It incorporates timeline tracking, approval workflows, and status management through a modular mixin architecture.
Model Structureβ
JobSchema = {
// Core Fields
jobId: String,
client: { type: ObjectId, ref: "Client" },
invoiceId: { type: ObjectId, ref: "Invoice" },
active: { type: Boolean, default: true },
status: { type: String, default: "New" },
note: String,
parentCompany: String,
author: { type: ObjectId, ref: "User" },
assignedTo: [{ type: ObjectId, ref: "Employee" }],
metadata: Mixed,
// Industry-Specific Fields
// Trucking
drivers: [{ type: ObjectId, ref: "User" }],
loadNumber: String,
legs: [{ type: ObjectId, ref: "Leg" }],
base: Number,
baseRate: Number,
fuelRate: Number,
flatRate: Number,
// Service/Repair
items: [{ type: ObjectId, refPath: "itemsModel" }],
location: Mixed,
customerSignature: String,
appointmentDate: Date,
// Financial Fields
salesTax: Number,
salesTaxRate: Number,
serviceFeeTotal: Number,
partsTotal: Number,
hourlyTotal: Number,
calculatedTotalCharges: Number,
};
Mixin Architectureβ
1. Timeline Mixinβ
// Tracks chronological events and changes
{
timeline: [TimelineItem],
methods: {
addTimelineItem(data),
getTimeline(query)
}
}
2. Status Mixinβ
// Manages job status transitions
{
status: String,
statusHistory: [{
status: String,
reason: String,
updatedBy: ObjectId,
updatedAt: Date
}],
methods: {
updateStatus(newStatus, reason, userId, description)
}
}
3. Approval Mixinβ
// Handles approval workflows
{
approval: {
status: enum["pending", "approved", "rejected"],
reviewedBy: ObjectId,
signature: String,
reviewedAt: Date,
notes: String,
history: [{
status: String,
updatedBy: ObjectId,
updatedAt: Date,
version: Number
}]
},
methods: {
updateApproval(status, user, notes, signature)
}
}
Endpointsβ
Job Managementβ
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /jobs | Create new job | User |
| GET | /jobs | List all jobs (paginated) | Client |
| GET | /jobs/:id | Get job by ID | Client |
| PUT | /jobs/:id | Update job | User |
| DELETE | /jobs | Delete jobs | Admin |
Job Itemsβ
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| PUT | /jobs/:id/items | Add job item | User |
| PUT | /jobs/:id/items/:itemId | Update job item | User |
| DELETE | /jobs/:id/items/:itemId | Delete job item | User |
| PUT | /jobs/:id/items/:itemId/complete | Complete item | User |
| PUT | /jobs/:id/items/:itemId/status | Update item status | User |
Approval Workflowβ
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /jobs/:id/proposal | Get client proposal | Client Token |
| PUT | /jobs/:id/reject | Reject job | Client Token |
| PUT | /jobs/:id/items-approval | Approve job items | Admin |
| POST | /jobs/:id/send-proposal | Send proposal email | User |
Industry-Specific Featuresβ
Trucking Industryβ
- Load tracking with multiple legs
- Driver assignment
- Fuel rate calculations
- Mileage tracking
- Rate management (base, fuel, flat)
Service/Repair Industryβ
- Work order items
- Parts management
- Service location tracking
- Customer signatures
- Appointment scheduling
Implementation Detailsβ
Security Featuresβ
- Role-based access control
- Client approval tokens
- Parent company verification
- User action tracking
Integration Pointsβ
- Client management
- Invoice generation
- Employee assignment
- Media attachments
- Email notifications
Best Practicesβ
-
Status Management
- Use status mixin for transitions
- Include reason for changes
- Maintain audit trail
-
Approval Workflow
- Version control for proposals
- Signature validation
- History tracking
- Client communication
-
Timeline Tracking
- Document all significant changes
- Include user context
- Maintain chronological order
Error Handlingβ
- Status transition validation
- Approval state conflicts
- Item management validation
- Rate calculation errors
Future Enhancementsβ
- Real-time status updates
- Advanced rate calculations
- Automated scheduling
- Enhanced reporting
- Mobile optimization
PDF Systemβ
Overviewβ
The PDF System provides a flexible and customizable document generation service that supports multiple document types (invoices, work orders, job proposals) with tenant-specific templating. It includes template management, dynamic content generation, and customizable styling.
Model Structureβ
PDFTemplateSchema = {
// Template Identification
name: { type: String, required: true },
type: { type: String, enum: ["invoice", "workOrder", "jobProposal"] },
version: { type: Number, default: 1 },
// Tenant Association
parentCompany: { type: ObjectId, ref: "Customer" },
// Template Content
html: { type: String, required: true },
css: { type: String, required: true },
settings: { type: Mixed, default: {} },
// Template Status
isDefault: { type: Boolean, default: false },
isSystemDefault: { type: Boolean, default: false },
// Audit Fields
createdBy: { type: ObjectId, ref: "User" },
updatedBy: { type: ObjectId, ref: "User" },
timestamps: true,
};
Endpointsβ
Template Managementβ
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /pdf/templates | List all templates | Yes |
| GET | /pdf/templates/default | Get default templates | Yes |
| GET | /pdf/templates/:id | Get template by ID | Yes |
| POST | /pdf/templates | Create new template | Yes |
| PUT | /pdf/templates/:id | Update template | Yes |
| DELETE | /pdf/templates/:id | Delete template | Yes |
| GET | /pdf/templates/default/:type | Get default template by type | Yes |
PDF Generationβ
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /pdf/generate | Generate PDF document | Yes |
Implementation Detailsβ
Template Systemβ
-
Template Types
- Invoice templates
- Work order templates
- Job proposal templates
-
Template Hierarchy
- System default templates
- Tenant default templates
- Custom templates
-
Template Components
- HTML structure
- CSS styling
- Custom settings
- Dynamic content placeholders
PDF Generation Serviceβ
-
Content Processing
- Dynamic data injection
- Variable replacement
- Conditional sections
- Table generation
-
Styling
- Custom CSS application
- Responsive layouts
- Print optimization
- Page breaks handling
-
Output Options
- File generation
- Stream handling
- Download options
- Storage integration
Security Featuresβ
-
Access Control
- Tenant isolation
- Template ownership
- Permission-based access
- Version control
-
Data Protection
- Sanitized content
- Secure storage
- Access logging
- Audit trail
Integration Pointsβ
-
Business Documents
- Invoice generation
- Work order creation
- Proposal formatting
- Custom documents
-
System Services
- Storage service
- Email service
- Document management
- Version control
-
External Systems
- Client portals
- Document viewers
- Archive systems
- Print services
Best Practicesβ
-
Template Management
- Maintain version control
- Use consistent styling
- Include fallback options
- Document template structure
-
Content Generation
- Validate dynamic content
- Handle missing data
- Implement error recovery
- Optimize performance
-
System Integration
- Use async processing
- Implement caching
- Handle large documents
- Monitor performance
Industry-Specific Featuresβ
Trucking Industryβ
- Bill of lading templates
- Load confirmation documents
- Rate confirmation sheets
- Driver payment statements
Service/Repair Industryβ
- Service quotes
- Work orders
- Inspection reports
- Completion certificates
Error Handlingβ
-
Template Errors
- Invalid HTML/CSS
- Missing placeholders
- Style conflicts
- Version mismatches
-
Generation Errors
- Missing data
- Format issues
- Size limitations
- Resource constraints
Future Enhancementsβ
- Template Editor UI
- Advanced styling options
- Dynamic template sections
- Batch processing
- Template analytics
Performance Considerationsβ
-
Generation Optimization
- Caching strategies
- Resource management
- Batch processing
- Queue management
-
Storage Management
- File compression
- Cleanup policies
- Archive strategies
- Version retention
Technical Implementationβ
PDF Service Architectureβ
- Browser Management
class PDFService {
constructor() {
this.browser = null;
this.isInitializing = false;
this.initPromise = null;
}
}
- Template Processing
-
Handlebars templating engine
-
Custom helpers for formatting:
// Date formatting
handlebars.registerHelper("formatDate", (date) =>
format(new Date(date), "MM/dd/yyyy")
);
// Money formatting
handlebars.registerHelper("formatMoney", (amount) => amount.toFixed(2));
-
PDF Generation Pipeline
- Browser initialization with Puppeteer
- Template retrieval and compilation
- Content rendering
- PDF conversion
- Resource cleanup
-
Performance Optimizations
- Browser instance reuse
- Request interception for resource control
- Timeout handling
- Error recovery
- Memory management
Configuration Optionsβ
{
templateId: String, // Specific template to use
type: String, // Template type (invoice, workOrder, etc.)
companyId: String, // Tenant identifier
orientation: String, // 'portrait' or 'landscape'
format: String // Page format (A4, Letter, etc.)
}
Resource Managementβ
-
Browser Instance
- Lazy initialization
- Health checking
- Automatic recovery
- Graceful shutdown
-
Page Handling
- Resource interception
- Memory optimization
- Timeout management
- Error boundaries
-
Template Caching
- Default template fallback
- Company-specific templates
- Version management
- Cache invalidation
Error Recovery Strategiesβ
-
Browser Issues
// Browser health check
try {
const pages = await this.browser.pages();
if (!pages) throw new Error("Browser unresponsive");
} catch (error) {
await this.browser.close();
this.browser = null;
// Reinitialize
} -
Template Failures
- Timeout handling
- Default template fallback
- Error logging
- User notification
-
Generation Errors
- Resource cleanup
- Error categorization
- Retry mechanisms
- Fallback options
Monitoring and Debuggingβ
-
Performance Metrics
console.time("browser-launch");
console.time("template-processing");
console.time("page-creation"); -
Error Tracking
- Detailed error logging
- Stack trace preservation
- Context capture
- Recovery tracking
-
Resource Usage
- Memory monitoring
- CPU utilization
- Browser instances
- Page lifecycle
Last Updated: [Current Date] Status: Active Version: 1.0