My App

CLAUDE

SmartCrew Admin - CLAUDE

CLAUDE.md

This file provides comprehensive guidance to Claude Code (claude.ai/code) when working with the SmartCrew Admin Console codebase.

Project Overview

SmartCrew Admin Console is a Flutter web application for managing construction projects. It provides comprehensive administrative interfaces for managing projects, labor, materials, equipment, customers, vendors, and generating reports.

Technology Stack

  • Framework: Flutter Web (Material Design)
  • State Management: Provider pattern with ChangeNotifier
  • Backend: Firebase (Auth, Firestore, Functions, Storage)
  • Code Generation: flutter_gen for assets, build_runner for various generators
  • Deployment: Firebase Hosting

Development Commands

Running the Application

# Start development server
flutter run -d web-server --web-hostname 0.0.0.0 --web-port 8080

# Run with specific browser
flutter run -d chrome

Building & Deployment

# Build for production
flutter build web

# Deploy to Firebase Hosting
firebase deploy --only hosting

Code Generation

# Generate code for assets, colors, fonts
flutter packages pub run build_runner build --delete-conflicting-outputs

# Watch mode for continuous generation
flutter packages pub run build_runner watch --delete-conflicting-outputs

Dependency Management

flutter pub get       # Install dependencies
flutter pub upgrade   # Upgrade dependencies
flutter pub outdated  # Check for outdated packages

Testing & Quality

flutter test          # Run unit tests
flutter analyze       # Static code analysis
flutter format .      # Format code

Environment Configuration

The app uses config.env file with these key variables:

  • FUNCTIONS_REGION: Cloud Functions region (default: us-central1)
  • PROJECT_NAME: SmartCrew
  • CURRENT_URL: Web app URL for deep linking

Project Structure

Root Directory

smartcrew_admin/
├── .firebase/          # Firebase hosting cache
├── ai/                 # AI-related scripts and configurations
├── assets/             # Static assets (images, icons, fonts)
├── build/              # Build output directory
├── lib/                # Main source code
├── web/                # Web-specific files (index.html, favicon, manifest)
├── config.env          # Environment configuration
├── firebase.json       # Firebase configuration
├── pubspec.yaml        # Flutter dependencies and project configuration
└── CLAUDE.md          # This file - project documentation for Claude

Core Library Structure (lib/)

/lib/main.dart

  • Entry point of the application
  • Initializes Firebase, environment variables, and providers
  • Sets up MultiProvider with all necessary providers
  • Configures routing and theme

/lib/providers/ - State Management Layer

All state management using Provider pattern with ChangeNotifier.

Core Providers:
  • auth_provider.dart: Manages Firebase authentication state, user sessions, and auth tokens
  • home_provider.dart: Controls navigation state, screen switching, and sidebar management
  • table_filter_controller.dart: Generic table filtering, pagination, and sorting logic
  • report_provider.dart: Report generation and management
  • users_data_provider.dart: User-specific data management
/lib/providers/network_data_providers/ - Data Fetching Layer

Central data management using mixin pattern:

  • network_data_provider.dart: Singleton that aggregates all data providers via mixins
    • Initializes all repositories on app startup
    • Manages Firebase Functions and Firestore instances
    • Orchestrates parallel data fetching

Domain-Specific Provider Mixins:

  • users_provider.dart: Employee/user management
  • project_provider.dart: Project CRUD operations
  • customers_provider.dart: Customer relationship management
  • vendors_provider.dart: Vendor/supplier management
  • materials_provider.dart: Construction materials inventory
  • equipment_provider.dart: Equipment tracking and management
  • equipment_category_provider.dart: Equipment categorization
  • activity_provider.dart: Activity logging and tracking
  • company_provider.dart: Company/organization settings
  • admin_log_provider.dart: Administrative action logging
  • document_provider.dart: Document management
  • time_off_provider.dart: Employee time-off requests
/lib/providers/ui_providers/ - UI State Management

UI-specific state providers for complex UI components

/lib/screens/ - Presentation Layer

/lib/screens/logged_out/
  • login_screen.dart: Authentication interface
  • forgot_password_screen.dart: Password recovery
/lib/screens/logged_in/ - Main Application Screens

Each feature follows this organizational pattern:

feature/
├── feature_screen.dart     # Main screen widget
├── tables/                  # Data table components
├── widgets/                 # Feature-specific widgets
├── modals/                  # Feature-specific modals
└── charts/                  # Visualization components

Feature Modules:

  • dashboard/: Main dashboard with statistics and overview

    • Real-time metrics display
    • Quick actions and navigation
    • Activity feed
  • labor/: Employee and labor management

    • Employee time tracking
    • Labor allocation to projects
    • Time card management
    • Payroll calculations
  • project/: Project management

    • Project creation and editing
    • Jobsite management
    • Resource allocation
    • Timeline tracking
  • materials/: Materials inventory

    • Inventory tracking
    • Usage reports
    • Purchase orders
    • Material allocation to projects
  • equipment/: Equipment management

    • Equipment inventory
    • Service records
    • Maintenance scheduling
    • Usage tracking
  • customers/: Customer relationship management

    • Customer profiles
    • Contact management
    • Project associations
    • Notes and communications
  • vendors/: Vendor management

    • Vendor profiles
    • Purchase history
    • Contract management
  • reports/: Reporting and analytics

    • Custom report generation
    • Data export functionality
    • Analytics dashboards
  • settings/: Application settings

    • User preferences
    • Company configuration
    • System settings
    • Integration configurations
  • tables/: Shared table components

    • Abstract base classes for tables
    • Common table widgets
    • Filtering and sorting utilities

/lib/services/ - Business Logic Layer

Domain-driven service organization for business logic:

Service Directory Structure:
  • base/: Base service classes and interfaces
  • activity/: Activity logging services
  • customer/: Customer-related business logic
  • dashboard/: Dashboard data aggregation
  • equipment/: Equipment lifecycle management
  • labor/: Complex labor calculations
    • time_card/: Time card processing
    • Various calculation services (daily, weekly, range)
  • log/: Logging services for different entities
  • material/: Material inventory logic
  • project/: Project management logic
  • report/: Report generation services
  • utils/: Shared utility services

/lib/models/ - Data Layer

Data models and DTOs:

Core Models:
  • User/Auth Models: app_user.dart, authentication data
  • Project Models: project.dart, jobsite.dart, location.dart
  • Resource Models: materials.dart, equipment.dart, labor.dart
  • Business Models: customer.dart, vendor.dart, company.dart
  • System Models: activity.dart, admin_log.dart, document.dart
  • Utility Models: status.dart, months.dart, currency.dart
/lib/models/log/ - Specialized Log Models

Various log types for different tracking needs

/lib/components/ - Reusable UI Components

Component Categories:
  • cards/: Reusable card components for data display
  • custom/: Custom widgets specific to the application
  • dropdowns/: Specialized dropdown components
  • modals/: Base modal classes and implementations
    • settings/: Settings modal with tabbed interface
    • settings/tabs/: Individual setting tabs
  • page_prefabs/: Pre-built page templates
Key Components:
  • search_box.dart: Universal search component
  • typeahead_textfield.dart: Auto-complete text input
  • shimmer_container.dart: Loading placeholder
  • video_thumbnail.dart: Video preview widget

/lib/util/ - Utilities and Helpers

Utility Categories:
  • adapter/: Data adapters and transformers (19 adapters)
  • extensions/: Dart extension methods (10 extensions)
    • String extensions
    • DateTime extensions
    • List extensions
    • Context extensions
Core Utilities:
  • app_dialog.dart: Dialog utilities
  • app_spacing.dart: Spacing constants and helpers
  • choose_file.dart: File picker utilities
  • loading.dart: Loading indicators
  • log_utils.dart: Logging utilities
  • text_styles.dart: Text style definitions
  • notifications_helper.dart: Toast/notification helpers

/lib/repositories/ - Data Access Layer

Repository pattern implementations for data access

/lib/gen/ - Generated Code

Auto-generated files (DO NOT EDIT MANUALLY):

  • assets.gen.dart: Type-safe asset references
  • colors.gen.dart: Color constants from design system
  • fonts.gen.dart: Font family definitions

Architecture Patterns

State Management Architecture

NetworkDataProvider (Singleton)
    ├── UsersProvider (Mixin)
    ├── ProjectProvider (Mixin)
    ├── CustomersProvider (Mixin)
    ├── VendorsProvider (Mixin)
    ├── MaterialsProvider (Mixin)
    ├── EquipmentProvider (Mixin)
    └── [Other Provider Mixins]

Data Flow Pattern

  1. Initialization: NetworkDataProvider.init() fetches all initial data in parallel
  2. State Updates: Providers notify listeners on data changes
  3. UI Reaction: Widgets rebuild using context.watch<Provider>()
  4. User Actions: UI triggers provider methods
  5. Backend Sync: Providers update Firestore/Functions
  6. Real-time Updates: Firestore listeners update provider state
  • Route Guard: Wraps all routes to check authentication
  • Screen Enum: Centralized screen definitions in HomeProvider
  • Dynamic Routing: Screen switching via HomeProvider.setScreen()
  • Responsive Layout: Adapts between wide and mobile layouts
class CustomModal extends StatelessWidget {
  static Future<void> show(BuildContext context, {required params}) {
    // Standard modal showing pattern
  }
}

Service Layer Pattern

Services encapsulate complex business logic:

  • Stateless service classes
  • Domain-specific organization
  • Testable business logic
  • Separation from UI and data layers

Key Conventions

Code Organization

  1. Feature-First Structure: Screens organized by feature, not by type
  2. Barrel Exports: Use index files for clean imports
  3. Mixin Composition: NetworkDataProvider uses mixins for separation of concerns
  4. Service Isolation: Business logic separated from UI and data access

Provider Usage Guidelines

// One-time read (actions)
context.read<MyProvider>().callMethod();

// Reactive updates (UI binding)
final data = context.watch<MyProvider>().property;

// Selective watching
final specific = context.select<MyProvider, SpecificType>((p) => p.specific);

Firebase Integration Points

  1. Authentication: Firebase Auth with custom claims
  2. Database: Firestore with offline support
  3. Functions: Cloud Functions for complex operations
  4. Storage: Firebase Storage for file uploads
  5. Hosting: Firebase Hosting for deployment

Responsive Design Approach

  • Breakpoints: Wide layout (>960px), Mobile layout (<960px)
  • Adaptive Widgets: Different widgets for different screen sizes
  • Flexible Layouts: Use Flex widgets for responsive design

Error Handling Strategy

  1. Try-catch blocks in service methods
  2. User-friendly error messages via toast notifications
  3. Logging errors to console in development
  4. Firebase Crashlytics in production

Performance Optimizations

  1. Lazy Loading: Load data on-demand
  2. Pagination: TableFilterController for large datasets
  3. Caching: Provider state caching
  4. Parallel Fetching: Future.wait for concurrent operations

Common Tasks

Adding a New Feature

  1. Create feature folder in /lib/screens/logged_in/
  2. Add provider mixin to NetworkDataProvider if needed
  3. Create service classes in /lib/services/
  4. Add models in /lib/models/
  5. Update HomeProvider with new screen enum
  6. Add navigation item to sidebar

Creating a New Modal

  1. Extend base modal class
  2. Implement static show() method
  3. Handle form validation and submission
  4. Use Provider for state management

Adding a New Table

  1. Create table widget in feature's tables/ folder
  2. Use TableFilterController for filtering/pagination
  3. Implement sorting and search
  4. Add export functionality if needed

Implementing a New Service

  1. Create service class in appropriate /lib/services/ subfolder
  2. Keep services stateless
  3. Return typed results
  4. Handle errors appropriately
  5. Write unit tests

Testing Strategy

Unit Tests

  • Test services independently
  • Mock Firebase dependencies
  • Test model serialization
  • Validate business logic

Widget Tests

  • Test individual components
  • Mock providers
  • Verify user interactions
  • Check responsive behavior

Integration Tests

  • Test complete user flows
  • Verify Firebase integration
  • Test real-time updates
  • Validate navigation

Deployment Checklist

  1. Run flutter analyze - fix any issues
  2. Run flutter test - ensure all tests pass
  3. Update version in pubspec.yaml
  4. Build production: flutter build web
  5. Test locally: firebase serve
  6. Deploy: firebase deploy
  7. Verify deployment at production URL
  8. Monitor error logs in Firebase Console

Performance Monitoring

Key Metrics to Track

  • Initial load time
  • Time to interactive
  • API response times
  • Memory usage
  • Frame rendering performance

Optimization Areas

  • Bundle size optimization
  • Image optimization
  • Lazy loading implementation
  • Code splitting
  • Tree shaking

Security Considerations

  1. Authentication: All routes protected by RouteGuard
  2. Authorization: Role-based access control via custom claims
  3. Data Validation: Client and server-side validation
  4. Sensitive Data: Never log sensitive information
  5. API Security: Cloud Functions validate auth tokens
  6. CORS Configuration: Properly configured for web

Troubleshooting Guide

Common Issues

  1. Provider Not Found: Ensure provider is added to MultiProvider
  2. Navigation Issues: Check HomeProvider screen enum
  3. Data Not Loading: Verify NetworkDataProvider initialization
  4. Build Errors: Run flutter clean and rebuild
  5. Firebase Errors: Check Firebase configuration and rules

Important Notes

  • Singleton Pattern: NetworkDataProvider is a singleton - use factory constructor
  • Async Initialization: Wait for NetworkDataProvider.init() before showing UI
  • Generated Files: Never edit files in /lib/gen/ - they're auto-generated
  • Environment Variables: Always use config.env for configuration
  • Code Style: Follow Flutter style guide and use flutter format
  • Commits: Write clear, descriptive commit messages
  • Documentation: Update this file when adding major features

External Dependencies

Key packages and their purposes:

  • provider: State management
  • firebase_*: Firebase integration
  • bot_toast: User notifications
  • data_table_2: Advanced data tables
  • flutter_gen: Code generation
  • intl: Internationalization
  • pdf: PDF generation for reports
  • syncfusion_flutter_charts: Data visualization

Contact & Support

For questions about the codebase architecture or development practices, consult the team lead or refer to the internal documentation.

On this page

CLAUDE.mdProject OverviewTechnology StackDevelopment CommandsRunning the ApplicationBuilding & DeploymentCode GenerationDependency ManagementTesting & QualityEnvironment ConfigurationProject StructureRoot DirectoryCore Library Structure (lib/)/lib/main.dart/lib/providers/ - State Management LayerCore Providers:/lib/providers/network_data_providers/ - Data Fetching Layer/lib/providers/ui_providers/ - UI State Management/lib/screens/ - Presentation Layer/lib/screens/logged_out//lib/screens/logged_in/ - Main Application Screens/lib/services/ - Business Logic LayerService Directory Structure:/lib/models/ - Data LayerCore Models:/lib/models/log/ - Specialized Log Models/lib/components/ - Reusable UI ComponentsComponent Categories:Key Components:/lib/util/ - Utilities and HelpersUtility Categories:Core Utilities:/lib/repositories/ - Data Access Layer/lib/gen/ - Generated CodeArchitecture PatternsState Management ArchitectureData Flow PatternNavigation ArchitectureModal System PatternService Layer PatternKey ConventionsCode OrganizationProvider Usage GuidelinesFirebase Integration PointsResponsive Design ApproachError Handling StrategyPerformance OptimizationsCommon TasksAdding a New FeatureCreating a New ModalAdding a New TableImplementing a New ServiceTesting StrategyUnit TestsWidget TestsIntegration TestsDeployment ChecklistPerformance MonitoringKey Metrics to TrackOptimization AreasSecurity ConsiderationsTroubleshooting GuideCommon IssuesImportant NotesExternal DependenciesContact & Support