=================================================================================== REPOSITORY GUIDELINES Laravel CRM & Marketing Platform =================================================================================== TABLE OF CONTENTS ----------------- 1. Project Overview 2. System Architecture 3. Module Organization 4. Authentication & Authorization 5. Database Schema 6. Build, Test & Development Commands 7. Coding Style & Conventions 8. Testing Guidelines 9. Commit & Pull Request Guidelines 10. Security & Configuration 11. API Integration 12. Deployment Guide =================================================================================== 1. PROJECT OVERVIEW =================================================================================== This is a comprehensive Laravel-based CRM and Marketing Platform with AI-powered features, team collaboration, social media management, and white-label capabilities. TECH STACK: ----------- - Backend: Laravel 12.x (PHP 8.2+) - Frontend: Blade Templates + Alpine.js + Tailwind CSS 3.x - Database: SQLite (default) / MySQL / PostgreSQL - Authentication: Laravel Breeze + Sanctum - Build Tools: Vite 7.x - Email: SMTP (Gmail, Mailtrap, etc.) - Queue: Database driver - Cache: Database driver - Storage: Local filesystem (public disk) KEY FEATURES: ------------- ✅ Multi-tenant company isolation ✅ Role-based access control (Admin, Manager, Member) ✅ Module-based permissions system ✅ AI Chat with image generation (Pollinations.ai) ✅ Team collaboration with real-time messaging ✅ Voice notes support in team chat ✅ Typing indicators ✅ Team invitation system with email notifications ✅ Social media integration (GetLate API) ✅ Popup-based OAuth connections ✅ Contact & Lead management ✅ Opportunity tracking ✅ Campaign management ✅ Email campaigns with SMTP ✅ Calendar & scheduling ✅ Reviews & reputation management ✅ Audit logging ✅ White-label support =================================================================================== 2. SYSTEM ARCHITECTURE =================================================================================== DIRECTORY STRUCTURE: -------------------- laravel-backend/ ├── app/ │ ├── Http/ │ │ ├── Controllers/ # Business logic controllers │ │ │ ├── Auth/ # Authentication controllers │ │ │ ├── Social/ # Social media OAuth controllers │ │ │ └── Api/ # API endpoints │ │ └── Middleware/ # Custom middleware │ │ ├── AdminMiddleware.php │ │ └── CheckModuleAccess.php │ ├── Models/ # Eloquent models (30+ models) │ ├── Mail/ # Mailable classes │ ├── Services/ # Business logic services │ ├── Traits/ # Reusable traits │ └── Policies/ # Authorization policies ├── database/ │ ├── migrations/ # Database schema migrations (75+ files) │ ├── seeders/ # Data seeders │ └── factories/ # Model factories ├── resources/ │ ├── views/ # Blade templates │ │ ├── layouts/ # Layout templates │ │ ├── auth/ # Authentication views │ │ ├── dashboard/ # Dashboard views │ │ ├── contacts/ # Contact management │ │ ├── conversations/ # Team chat │ │ ├── team/ # Team management │ │ ├── ai-chat/ # AI chat interface │ │ ├── getlate/ # Social media profiles │ │ └── emails/ # Email templates │ ├── css/ # Tailwind CSS │ └── js/ # Alpine.js & Axios ├── routes/ │ ├── web.php # Web routes │ ├── api.php # API routes │ ├── auth.php # Authentication routes │ └── console.php # Artisan commands ├── storage/ │ ├── app/ │ │ └── public/ # Public storage │ │ ├── ai-images/ # AI-generated images │ │ └── voice-notes/ # Voice recordings │ ├── framework/ # Framework cache │ └── logs/ # Application logs ├── public/ │ ├── storage/ # Symlink to storage/app/public │ └── build/ # Compiled assets (Vite) └── tests/ ├── Feature/ # Feature tests └── Unit/ # Unit tests =================================================================================== 3. MODULE ORGANIZATION =================================================================================== The system uses a modular architecture with granular access control. CORE MODULES: ------------- 1. Dashboard - Overview & analytics 2. Contacts - Contact management (ContactController) 3. Opportunities - Sales pipeline (OpportunityController) 4. Conversations - Team chat & messaging (ConversationController) 5. Activities - Activity tracking (ActivityController) 6. Campaigns - Marketing campaigns (CampaignController) 7. Social Posts - Social media posts (SocialPostController) 8. Email Campaigns - Email marketing (EmailCampaignController) 9. AI Agents - AI assistants (AIAgentController, AIChatController) 10. Media - File management (MediaController) 11. Calendar - Event scheduling (CalendarController) 12. Reviews - Reputation management (ReviewController) 13. Subscriptions - Billing & subscriptions (SubscriptionController) 14. Team - Team management (TeamController) 15. Audit Logs - Activity auditing (AuditLogController) 16. Settings - System settings (SettingsController) 17. Integrations - Third-party integrations (IntegrationController) 18. GetLate Profiles - Social media profiles (GetLateProfileController) 19. User Access Control - Permission management (UserAccessController) MODULE ACCESS CONTROL: ---------------------- Each module has a slug (e.g., 'contacts', 'opportunities') that determines access. Database Tables: - modules: Stores available modules - user_module_access: Maps users to modules with access level Access Levels: - allowed: User can access the module - denied: User cannot access the module Middleware: CheckModuleAccess - Applied to routes: ->middleware('module.access:contacts') - Checks if user has permission to access the module - Admins bypass all module checks =================================================================================== 4. AUTHENTICATION & AUTHORIZATION =================================================================================== AUTHENTICATION SYSTEM: ---------------------- Framework: Laravel Breeze (session-based authentication) API: Laravel Sanctum (token-based for API) User Roles: ----------- 1. ADMIN - Full system access - Bypass all module restrictions - Can manage users and permissions - Can invite team members - Access to User Access Control 2. MANAGER - Can manage team members - Can invite new members - Limited to assigned modules - Can view team conversations 3. MEMBER - Basic access - Limited to assigned modules - Can participate in team conversations - Cannot invite or manage users MIDDLEWARE: ----------- 1. AdminMiddleware (app/Http/Middleware/AdminMiddleware.php) - Checks if user role is 'admin' or 'ADMIN' - Returns 403 if not admin - Applied to admin-only routes 2. CheckModuleAccess (app/Http/Middleware/CheckModuleAccess.php) - Checks if user has access to specific module - Admins bypass this check - Returns 403 if access denied - Applied to module routes: ->middleware('module.access:module_slug') AUTHORIZATION FLOW: ------------------- 1. User logs in via /login (Laravel Breeze) 2. Session created with user data 3. Middleware checks on each request: - Is user authenticated? (auth middleware) - Is user admin? (AdminMiddleware for admin routes) - Does user have module access? (CheckModuleAccess for module routes) 4. User model method hasModuleAccess($moduleSlug) checks permissions COMPANY ISOLATION: ------------------ - All users belong to a company (company_id) - Data is filtered by company_id in queries - Users can only see data from their company - Team invitations are company-scoped - Team conversations are company-scoped =================================================================================== 5. DATABASE SCHEMA =================================================================================== DATABASE: SQLite (default), MySQL, PostgreSQL supported KEY TABLES: ----------- CORE TABLES: 1. companies - id, name, domain, logo, settings, created_at, updated_at 2. users - id, name, email, password, avatar, role, company_id, is_active - occupation, phone, bio, last_login_at, created_at, updated_at 3. modules - id, name, slug, description, icon, is_active, created_at, updated_at 4. user_module_access - id, user_id, module_id, access (allowed/denied), created_at, updated_at TEAM MANAGEMENT: 5. team_invitations - id, company_id, email, role, token (64 chars), status, invited_by - expires_at, accepted_at, created_at, updated_at 6. team_rooms - id, company_id, name, description, type (GROUP/DIRECT), created_at 7. team_messages - id, team_room_id, user_id, content, type (text/voice), file_url - created_at, updated_at 8. team_members - id, user_id, company_id, role, permissions, created_at, updated_at CRM TABLES: 9. contacts - id, user_id, company_id, name, email, phone, company, position - source, tags, notes, created_at, updated_at 10. opportunities - id, user_id, company_id, contact_id, title, value, stage, probability - expected_close_date, notes, created_at, updated_at 11. conversations - id, user_id, company_id, contact_id, subject, status, priority - created_at, updated_at 12. activities - id, user_id, company_id, contact_id, opportunity_id, type, description - due_date, completed_at, created_at, updated_at AI & AUTOMATION: 13. ai_agents - id, user_id, company_id, name, type, prompt, model, settings - is_active, created_at, updated_at 14. ai_conversations - id, ai_agent_id, user_id, session_id, created_at, updated_at 15. chat_messages - id, ai_conversation_id, role (user/assistant), content, metadata - created_at, updated_at MARKETING: 16. campaigns - id, user_id, company_id, name, type, status, budget, start_date - end_date, created_at, updated_at 17. email_campaigns - id, user_id, company_id, name, subject, content, status - scheduled_at, sent_at, created_at, updated_at 18. social_posts - id, user_id, company_id, content, platforms, status, scheduled_at - published_at, created_at, updated_at SOCIAL MEDIA: 19. social_accounts - id, user_id, company_id, platform, account_id, username, access_token - refresh_token, expires_at, created_at, updated_at 20. getlate_profiles - id, user_id, company_id, name, description, settings - created_at, updated_at OTHER: 21. calendar_events 22. reviews 23. subscriptions 24. invoices 25. media_files 26. audit_logs 27. notifications 28. integrations 29. white_labels 30. email_templates =================================================================================== 6. BUILD, TEST & DEVELOPMENT COMMANDS =================================================================================== INITIAL SETUP: -------------- # Clone repository git clone cd laravel-backend # Install PHP dependencies composer install # Install Node dependencies npm install # Copy environment file copy .env.example .env # Windows cp .env.example .env # Linux/Mac # Generate application key php artisan key:generate # Create database file (SQLite) type nul > database/database.sqlite # Windows touch database/database.sqlite # Linux/Mac # Run migrations php artisan migrate # Seed database with sample data php artisan db:seed # Create storage symlink php artisan storage:link # Build frontend assets npm run build DEVELOPMENT COMMANDS: --------------------- # Start development server (all services) composer dev # This runs: server + queue + logs + vite concurrently # OR run services individually: php artisan serve # Start Laravel server (http://127.0.0.1:8000) php artisan queue:listen # Start queue worker php artisan pail # View logs in real-time npm run dev # Start Vite dev server # Clear caches php artisan cache:clear # Clear application cache php artisan config:clear # Clear config cache php artisan route:clear # Clear route cache php artisan view:clear # Clear compiled views # Database operations php artisan migrate # Run migrations php artisan migrate:fresh # Drop all tables and re-migrate php artisan migrate:fresh --seed # Fresh migration + seed data php artisan db:seed # Run seeders php artisan db:seed --class=UserSeeder # Run specific seeder # Tinker (Laravel REPL) php artisan tinker # Interactive shell BUILD COMMANDS: --------------- # Production build npm run build # Build assets for production # Development build npm run dev # Build with hot reload TESTING COMMANDS: ----------------- # Run all tests php artisan test # Run specific test file php artisan test tests/Feature/AuthTest.php # Run with coverage php artisan test --coverage # Run PHPUnit directly vendor/bin/phpunit CODE QUALITY: ------------- # Format code (Laravel Pint) vendor/bin/pint # Fix code style issues # Check code style without fixing vendor/bin/pint --test =================================================================================== 7. CODING STYLE & NAMING CONVENTIONS =================================================================================== PHP CODE STYLE: --------------- Follow PSR-12 coding standard (enforced by Laravel Pint) Indentation: 4 spaces (no tabs) Line Length: 120 characters max Encoding: UTF-8 without BOM NAMING CONVENTIONS: ------------------- Classes: - PascalCase: UserController, TeamInvitation, CheckModuleAccess - Singular nouns for models: User, Contact, Opportunity - Suffix controllers with "Controller": ContactController - Suffix middleware with "Middleware": AdminMiddleware Methods: - camelCase: getUserData(), sendTeamMessage(), hasModuleAccess() - Descriptive names: getTeamMessages() not getMessages() - Boolean methods start with "is", "has", "can": isActive(), hasAccess() Variables: - camelCase: $userId, $teamMembers, $isActive - Descriptive names: $teamMessage not $tm - Avoid abbreviations unless common: $id, $url, $api Database: - Tables: snake_case, plural: users, team_messages, user_module_access - Columns: snake_case: user_id, created_at, is_active - Foreign keys: singular_table_id: user_id, company_id - Pivot tables: alphabetical order: module_user not user_module Routes: - Kebab-case: /team-members, /ai-chat, /user-access - RESTful naming: /contacts, /contacts/{id}, /contacts/{id}/edit - Nested resources: /getlate/profiles/{profile}/connect Views: - Kebab-case: team-invitation.blade.php, accept-invitation.blade.php - Folder structure mirrors routes: views/team/index.blade.php BLADE TEMPLATES: ---------------- - Use @extends, @section, @yield for layouts - Use @include for partials - Use @component for reusable components - Escape output: {{ $variable }} not {!! $variable !!} - Use @auth, @guest for authentication checks - Use @can for authorization checks JAVASCRIPT: ----------- - camelCase for variables and functions - PascalCase for classes - Use const/let, avoid var - Use arrow functions: () => {} - Use template literals: `Hello ${name}` CSS/TAILWIND: ------------- - Use Tailwind utility classes - Follow mobile-first approach - Use responsive prefixes: sm:, md:, lg:, xl: - Group related utilities: flex items-center gap-2 - Use @apply sparingly in custom CSS =================================================================================== 8. TESTING GUIDELINES =================================================================================== TESTING FRAMEWORK: ------------------ PHPUnit 11.x (included with Laravel) TEST STRUCTURE: --------------- tests/ ├── Feature/ # Integration tests (HTTP, database) │ ├── AuthTest.php │ ├── ContactTest.php │ └── TeamTest.php └── Unit/ # Unit tests (isolated logic) ├── UserTest.php └── ModuleTest.php NAMING CONVENTIONS: ------------------- - Test classes: PascalCase + "Test" suffix: UserTest, ContactControllerTest - Test methods: test_snake_case_description or testCamelCaseDescription - Use descriptive names: test_user_can_create_contact() WRITING TESTS: -------------- Feature Test Example: ```php public function test_user_can_view_contacts() { $user = User::factory()->create(); $response = $this->actingAs($user)->get('/contacts'); $response->assertStatus(200); $response->assertViewIs('contacts.index'); } ``` Unit Test Example: ```php public function test_user_has_module_access() { $user = User::factory()->create(); $module = Module::factory()->create(['slug' => 'contacts']); UserModuleAccess::create([ 'user_id' => $user->id, 'module_id' => $module->id, 'access' => 'allowed' ]); $this->assertTrue($user->hasModuleAccess('contacts')); } ``` ASSERTIONS: ----------- HTTP: - assertStatus(200) - assertRedirect('/dashboard') - assertViewIs('contacts.index') - assertSee('Contact Name') - assertJson(['success' => true]) Database: - assertDatabaseHas('users', ['email' => 'test@example.com']) - assertDatabaseMissing('users', ['email' => 'deleted@example.com']) - assertDatabaseCount('contacts', 5) Authentication: - assertAuthenticated() - assertGuest() COVERAGE REQUIREMENTS: ---------------------- - Aim for 70%+ code coverage - All controllers should have feature tests - All models should have unit tests for custom methods - Critical business logic must be tested RUNNING TESTS: -------------- # All tests php artisan test # Specific test php artisan test --filter=test_user_can_create_contact # With coverage php artisan test --coverage # Stop on failure php artisan test --stop-on-failure =================================================================================== 9. COMMIT & PULL REQUEST GUIDELINES =================================================================================== COMMIT MESSAGE FORMAT: ---------------------- Use conventional commits format: ():