Overview
ElectroFix AI is built as a multi-tenant SaaS application where multiple companies (tenants) share the same application infrastructure while maintaining complete data isolation. Each company has its own isolated data scope, ensuring that users can only access and modify data belonging to their company.Core Concepts
Company Isolation
Every company in ElectroFix AI is a separate tenant with:- Unique company record with business details
- Isolated users, customers, orders, and inventory
- Separate subscription and AI usage tracking
- Independent billing and financial data
The company_id Foreign Key
The foundation of multi-tenancy is the company_id foreign key present in nearly every database table:
Company Relationships
TheCompany model defines relationships to all tenant-scoped resources:
Data Scoping in Practice
Controller-Level Scoping
Every controller enforces company-level data isolation. Here’s an example from theOrderController:
Service-Level Validation
TheOrderCreationService validates that related entities belong to the same company:
Model-Level Scopes
TheUser model includes a query scope for company filtering:
Multi-Tenant Data Models
Customer Model
Equipment Model
Inventory Item Model
Security Considerations
1. Always Validate Company Ownership
Before performing any operation, verify that the authenticated user has access to the resource:2. Use Database Constraints
Foreign key constraints ensure referential integrity:3. Never Trust Client Input
Always derivecompany_id from the authenticated user, never from request data:
4. Developer Role Exception
Thedeveloper role has cross-company access for administrative purposes:
Database Indexes
For optimal performance, compound indexes are created oncompany_id:
Common Patterns
Pattern 1: Controller Queries
Pattern 2: Creating Records
Pattern 3: Cross-Model Validation
Best Practices
- Always scope by company_id in queries for non-developer users
- Use model relationships to navigate between tenant-scoped resources
- Validate cross-model relationships to prevent data leakage
- Add database indexes on
company_idfor performance - Test isolation thoroughly to ensure no cross-tenant data access
- Use consistent authorization patterns across all controllers
Related Topics
- Roles & Permissions - User access control
- Subscription Plans - Company-level subscriptions
- AI Diagnostics - Company AI usage tracking