Skip to main content

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​

MethodEndpointDescriptionAuthentication Required
POST/api/v1/account/loginUser authenticationNo
POST/api/v1/account/logoutSession terminationYes
GET/api/v1/account/currentGet current user infoYes
POST/api/v1/account/forgot/passwordPassword recoveryNo
PUT/api/v1/account/updateUpdate user profileYes
PUT/api/v1/account/activateAccount activationYes
PUT/api/v1/account/verify/tokenToken verificationYes
POST/api/v1/account/change/passwordPassword changeYes
POST/api/v1/account/refreshToken refreshNo

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 model
  • Token: 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​

  1. All passwords are hashed before storage
  2. Tokens are validated on protected routes
  3. Email notifications for security-related actions
  4. Session management for multi-device support
  5. 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​

  1. Two-factor authentication support
  2. OAuth integration
  3. Enhanced session analytics
  4. Role-based access control improvements
  5. 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​

MethodEndpointDescriptionAuthentication Required
POST/api/v1/usersCreate new userYes + Admin
GET/api/v1/usersList all users (paginated)Yes + Admin
GET/api/v1/users/:idGet user by IDYes + Admin
PUT/api/v1/users/:idUpdate userYes + Admin
DELETE/api/v1/users/:idDelete userYes + Admin
DELETE/api/v1/usersBulk delete usersYes + Admin
POST/api/v1/users/email/:idSend email to userYes + 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 verification
  • admin: Role verification
  • verifyParent: Parent company verification
  • superAdmin: Super admin verification
  • paginationHandler: Pagination processing

Services​

  • Email/Mailer service
  • User management utilities
  • Pagination utilities

Best Practices​

  1. Always verify user permissions before operations
  2. Implement pagination for list operations
  3. Validate parent company relationships
  4. Maintain audit trail of user changes
  5. 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​

  1. Advanced role management
  2. User activity tracking
  3. Enhanced bulk operations
  4. Improved audit logging
  5. 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​

  1. Tenant Isolation

    • Always scope queries by customer/parentCompany
    • Validate cross-tenant data access
    • Maintain separate configurations
  2. Industry Specifics

    • Use appType for feature toggling
    • Implement industry-specific validations
    • Maintain separate business logic where needed
  3. 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​

  1. Enhanced metadata schema validation
  2. Advanced industry-specific configurations
  3. Improved tenant isolation patterns
  4. Extended business type support
  5. 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​

MethodEndpointDescriptionAuth Required
POST/jobsCreate new jobUser
GET/jobsList all jobs (paginated)Client
GET/jobs/:idGet job by IDClient
PUT/jobs/:idUpdate jobUser
DELETE/jobsDelete jobsAdmin

Job Items​

MethodEndpointDescriptionAuth Required
PUT/jobs/:id/itemsAdd job itemUser
PUT/jobs/:id/items/:itemIdUpdate job itemUser
DELETE/jobs/:id/items/:itemIdDelete job itemUser
PUT/jobs/:id/items/:itemId/completeComplete itemUser
PUT/jobs/:id/items/:itemId/statusUpdate item statusUser

Approval Workflow​

MethodEndpointDescriptionAuth Required
GET/jobs/:id/proposalGet client proposalClient Token
PUT/jobs/:id/rejectReject jobClient Token
PUT/jobs/:id/items-approvalApprove job itemsAdmin
POST/jobs/:id/send-proposalSend proposal emailUser

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​

  1. Status Management

    • Use status mixin for transitions
    • Include reason for changes
    • Maintain audit trail
  2. Approval Workflow

    • Version control for proposals
    • Signature validation
    • History tracking
    • Client communication
  3. 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​

  1. Real-time status updates
  2. Advanced rate calculations
  3. Automated scheduling
  4. Enhanced reporting
  5. 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​

MethodEndpointDescriptionAuth Required
GET/pdf/templatesList all templatesYes
GET/pdf/templates/defaultGet default templatesYes
GET/pdf/templates/:idGet template by IDYes
POST/pdf/templatesCreate new templateYes
PUT/pdf/templates/:idUpdate templateYes
DELETE/pdf/templates/:idDelete templateYes
GET/pdf/templates/default/:typeGet default template by typeYes

PDF Generation​

MethodEndpointDescriptionAuth Required
POST/pdf/generateGenerate PDF documentYes

Implementation Details​

Template System​

  1. Template Types

    • Invoice templates
    • Work order templates
    • Job proposal templates
  2. Template Hierarchy

    • System default templates
    • Tenant default templates
    • Custom templates
  3. Template Components

    • HTML structure
    • CSS styling
    • Custom settings
    • Dynamic content placeholders

PDF Generation Service​

  1. Content Processing

    • Dynamic data injection
    • Variable replacement
    • Conditional sections
    • Table generation
  2. Styling

    • Custom CSS application
    • Responsive layouts
    • Print optimization
    • Page breaks handling
  3. Output Options

    • File generation
    • Stream handling
    • Download options
    • Storage integration

Security Features​

  1. Access Control

    • Tenant isolation
    • Template ownership
    • Permission-based access
    • Version control
  2. Data Protection

    • Sanitized content
    • Secure storage
    • Access logging
    • Audit trail

Integration Points​

  1. Business Documents

    • Invoice generation
    • Work order creation
    • Proposal formatting
    • Custom documents
  2. System Services

    • Storage service
    • Email service
    • Document management
    • Version control
  3. External Systems

    • Client portals
    • Document viewers
    • Archive systems
    • Print services

Best Practices​

  1. Template Management

    • Maintain version control
    • Use consistent styling
    • Include fallback options
    • Document template structure
  2. Content Generation

    • Validate dynamic content
    • Handle missing data
    • Implement error recovery
    • Optimize performance
  3. 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​

  1. Template Errors

    • Invalid HTML/CSS
    • Missing placeholders
    • Style conflicts
    • Version mismatches
  2. Generation Errors

    • Missing data
    • Format issues
    • Size limitations
    • Resource constraints

Future Enhancements​

  1. Template Editor UI
  2. Advanced styling options
  3. Dynamic template sections
  4. Batch processing
  5. Template analytics

Performance Considerations​

  1. Generation Optimization

    • Caching strategies
    • Resource management
    • Batch processing
    • Queue management
  2. Storage Management

    • File compression
    • Cleanup policies
    • Archive strategies
    • Version retention

Technical Implementation​

PDF Service Architecture​

  1. Browser Management
class PDFService {
constructor() {
this.browser = null;
this.isInitializing = false;
this.initPromise = null;
}
}
  1. 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));
  1. PDF Generation Pipeline

    • Browser initialization with Puppeteer
    • Template retrieval and compilation
    • Content rendering
    • PDF conversion
    • Resource cleanup
  2. 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​

  1. Browser Instance

    • Lazy initialization
    • Health checking
    • Automatic recovery
    • Graceful shutdown
  2. Page Handling

    • Resource interception
    • Memory optimization
    • Timeout management
    • Error boundaries
  3. Template Caching

    • Default template fallback
    • Company-specific templates
    • Version management
    • Cache invalidation

Error Recovery Strategies​

  1. 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
    }
  2. Template Failures

    • Timeout handling
    • Default template fallback
    • Error logging
    • User notification
  3. Generation Errors

    • Resource cleanup
    • Error categorization
    • Retry mechanisms
    • Fallback options

Monitoring and Debugging​

  1. Performance Metrics

    console.time("browser-launch");
    console.time("template-processing");
    console.time("page-creation");
  2. Error Tracking

    • Detailed error logging
    • Stack trace preservation
    • Context capture
    • Recovery tracking
  3. Resource Usage

    • Memory monitoring
    • CPU utilization
    • Browser instances
    • Page lifecycle

Last Updated: [Current Date] Status: Active Version: 1.0