1. White-Level Architecture
 



# HADDU Multi-Tenant / White-Label Architecture

## Overview

HADDU follows a **white-label (multi-tenant) architecture** that allows multiple client applications to be managed from a **single Flutter codebase**.

Instead of maintaining separate Flutter projects for each client, the application dynamically loads client-specific configurations using the application's **Bundle ID / Package Name**.

This architecture enables:

* Single codebase for all clients
* Dynamic branding
* Dynamic themes
* Dynamic feature management
* Dynamic API configuration
* Easier onboarding of new clients
* Simplified CI/CD pipeline
* Reduced maintenance cost

---

# Architecture Flow

```text
Flutter App
    ↓
PackageInfo.packageName
    ↓
Bundle ID
    ↓
Client Config API
    ↓
Client Configuration
    ↓
Theme + Branding + Features + URLs
```

---

# Runtime Configuration

All client-specific configurations are managed through a centralized configuration model.

```dart
abstract class AppConfig {
  // App Information
  String get appName;
  String get appVersion;
  String get bundleId;

  // Branding
  String get logoUrl;
  String get introSvgUrl;
  String get introText;

  // Theme
  AppThemeConfig get theme;

  // Network
  String get baseUrl;
  String get webSocketUrl;
  String get apiKey;

  // Maps
  String get mapApiKey;
  String get mapTheme;

  // Localization
  List<String> get supportedLanguages;
  String get defaultLanguage;

  // Features
  bool get enableLogs;
  bool get enableAnalytics;

  // Firebase
  String get firebaseProjectId;

  // Future Features
  Map<String, dynamic> get featureFlags;
}
```

---

# Client Configuration API

All client configurations should be served from a backend API.

## Endpoint

```http
GET /client-config?bundleId=com.optrack.app
```

## Example Response

```json
{
  "bundleId": "com.optrack.app",
  "appName": "Optrack",
  "logoUrl": "https://cdn/logo.png",
  "introSvg": "https://cdn/intro.svg",
  "introText": "Welcome to Optrack",

  "theme": {
    "primaryColor": "#FF6600",
    "secondaryColor": "#000000",
    "darkPrimaryColor": "#111111"
  },

  "baseUrl": "https://api.optrack.com",
  "websocketUrl": "wss://socket.optrack.com",

  "firebaseProjectId": "optrack-prod",

  "mapApiKey": "xxxxx",

  "featureFlags": {
    "attendance": true,
    "chat": false,
    "inventory": true
  }
}
```

---

# Detect Bundle ID

The application identifies the client by reading the package name at runtime.

```dart
import 'package:package_info_plus/package_info_plus.dart';

final packageInfo = await PackageInfo.fromPlatform();

final bundleId = packageInfo.packageName;
```

Examples:

```text
com.optrack.app
com.haddu.app
com.client1.app
com.client2.app
```

---

# Load Configuration

During application startup, fetch the client configuration.

```dart
Future<AppConfigModel> loadConfig() async {
  final packageInfo = await PackageInfo.fromPlatform();

  final bundleId = packageInfo.packageName;

  final response = await dio.get(
    '/client-config',
    queryParameters: {
      'bundleId': bundleId,
    },
  );

  return AppConfigModel.fromJson(response.data);
}
```

---

# Config Manager

Centralized access to configuration.

```dart
class ConfigManager {
  static late AppConfigModel config;

  static Future<void> init() async {
    config = await loadConfig();
  }
}
```

Usage:

```dart
ConfigManager.config.appName;
ConfigManager.config.baseUrl;
ConfigManager.config.logoUrl;
```

---

# Dynamic Theme Management

## Theme Model

```dart
class AppThemeConfig {
  final String primaryColor;
  final String secondaryColor;
  final String backgroundColor;
  final String darkPrimaryColor;
}
```

## Build Theme Dynamically

```dart
ThemeData buildTheme(AppThemeConfig config) {
  return ThemeData(
    primaryColor: HexColor(config.primaryColor),
  );
}
```

---

# Dynamic Branding

## Logo

```dart
CachedNetworkImage(
  imageUrl: ConfigManager.config.logoUrl,
)
```

## Intro SVG

```dart
SvgPicture.network(
  ConfigManager.config.introSvgUrl,
)
```

Benefits:

* Branding updates without app release
* Client-specific visuals
* Centralized asset management

---

# Feature Flags

Features can be enabled or disabled per client.

## Example

```json
{
  "featureFlags": {
    "attendance": true,
    "chat": false,
    "inventory": true,
    "geofencing": true
  }
}
```

## Usage

```dart
if (ConfigManager.config.featureFlags['chat']) {
  showChat();
}
```

Benefits:

* Controlled rollouts
* Client-specific modules
* Faster experimentation

---

# Environment Configuration

Each client may have different environments.

```json
{
  "development": {
    "baseUrl": "https://dev-api.client.com"
  },
  "testing": {
    "baseUrl": "https://uat-api.client.com"
  },
  "production": {
    "baseUrl": "https://api.client.com"
  }
}
```

Environment definition:

```dart
enum Environment {
  dev,
  qa,
  prod,
}
```

Usage:

```dart
baseUrl =
    config.environments[currentEnvironment].baseUrl;
```

---

# Firebase Strategy

Firebase configuration cannot be fully dynamic.

Each client requires its own Firebase project.

## Android

```text
android/app/src/optrack/google-services.json

android/app/src/haddu/google-services.json

android/app/src/client1/google-services.json
```

## iOS

```text
ios/firebase/optrack/GoogleService-Info.plist

ios/firebase/haddu/GoogleService-Info.plist

ios/firebase/client1/GoogleService-Info.plist
```

The CI/CD pipeline copies the appropriate Firebase file during build.

---

# Android Flavors

Create product flavors for each client.

```gradle
productFlavors {

    optrack {
        applicationId "com.optrack.app"
    }

    haddu {
        applicationId "com.haddu.app"
    }

    client1 {
        applicationId "com.client1.app"
    }
}
```

Build command:

```bash
flutter build apk --flavor optrack

flutter build apk --flavor haddu
```

---

# iOS Schemes

Create separate schemes:

```text
Optrack
Haddu
Client1
```

Each scheme uses a different bundle identifier.

Examples:

```text
com.optrack.app

com.haddu.app

com.client1.app
```

---

# CI/CD Strategy

Maintain a client registry.

```yaml
clients:
  - optrack
  - haddu
  - client1
  - client2
  - client3
```

Pipeline:

```bash
for client in clients
do
  flutter build apk --flavor $client
  flutter build appbundle --flavor $client
  flutter build ipa --flavor $client
done
```

Result:

```text
100 Clients
    ↓
1 Pipeline Run
    ↓
100 APKs
100 AABs
100 IPAs
```

Each build automatically uses:

* Bundle ID
* Firebase configuration
* App icons
* Splash assets
* Theme
* API endpoints
* Localization
* Feature flags

---

# Native vs Dynamic Configuration

| Item                | Dynamic From Server | Native Build Required |
| ------------------- | ------------------- | --------------------- |
| Bundle ID           | ❌                   | ✅                     |
| App Icon            | ❌                   | ✅                     |
| Firebase Config     | ❌                   | ✅                     |
| Google Maps API Key | ❌                   | ✅                     |
| Deep Links          | ❌                   | ✅                     |
| Push Notifications  | ❌                   | ✅                     |
| Store Listing Name  | ❌                   | ✅                     |
| Splash Assets       | ❌                   | ✅                     |
| Base URL            | ✅                   | ❌                     |
| Theme Colors        | ✅                   | ❌                     |
| Feature Flags       | ✅                   | ❌                     |
| Localization        | ✅                   | ❌                     |
| Intro Screens       | ✅                   | ❌                     |
| WebSocket URL       | ✅                   | ❌                     |
| Branding Assets     | ✅                   | ❌                     |

---

# Recommended Strategy

Keep only the following per flavor:

* Bundle ID
* Firebase Configuration
* App Icons
* Splash Assets
* Maps API Keys
* Deep Link Configuration
* Store Metadata

Everything else should be delivered through the **Client Configuration API**:

* App Name
* Logos
* Theme Colors
* Base URLs
* WebSocket URLs
* Feature Flags
* Localization
* Intro Screens
* Analytics Configuration
* Future Client Settings

This approach allows onboarding a new client by simply adding a new configuration entry in the backend without requiring Flutter code changes.





















# Haddu Project Architecture Guide

This project is a Flutter-based GPS tracking app with features such as authentication, onboarding, device tracking, geofences, notifications, reports, and map-based views. The codebase is organized in a layered structure so the UI, business logic, data access, and shared services stay separate.

## 1. How the app flow works

The app starts from [lib/main.dart](lib/main.dart) and follows this flow:

1. Flutter bindings are initialized.
2. Environment config is loaded from [lib/config/env_config.dart](lib/config/env_config.dart).
3. Firebase is initialized.
4. Dependency injection is set up with [lib/config/dependency_injection/injection_container.dart](lib/config/dependency_injection/injection_container.dart).
5. Notification service is initialized.
6. The app runs through [lib/app.dart](lib/app.dart), which creates the root widget and providers.

### Startup flow

- [lib/main.dart](lib/main.dart)
  - initializes app services
  - loads environment config
  - registers dependencies
  - starts the app

- [lib/app.dart](lib/app.dart)
  - creates the main MaterialApp
  - provides BLoC instances
  - sets router, theme, and navigation

## 2. Main project structure

```text
lib/
  main.dart
  app.dart
  config/                 # env config + dependency injection
  core/                   # shared services, theme, navigation, network, storage
  features/               # feature modules
    common_features/      # auth, onboarding, language, notifications, etc.
    core_gps_module/      # devices, maps, geofences, reports, alerts
```

### Core folders

- [lib/config](lib/config)
  - environment setup
  - dependency injection modules

- [lib/core](lib/core)
  - shared widgets
  - theme and responsive helpers
  - network and storage services
  - navigation and utilities

- [lib/features](lib/features)
  - feature-specific UI, blocs, repositories, use cases, and data sources

## 3. How the app architecture works

This project follows a simple clean architecture style:

- Presentation layer
  - Screens and widgets
  - BLoC classes
  - UI state handling

- Domain layer
  - Use cases
  - repository contracts
  - business rules

- Data layer
  - repositories implementation
  - remote/local data sources
  - DTOs and models

- Core layer
  - API client, storage, logging, router, theme, helpers

### Simple request flow

UI -> BLoC -> UseCase -> Repository -> Data Source -> API/Storage

Example:

- Login screen sends an event to AuthBloc
- AuthBloc calls a use case
- Use case calls the repository
- Repository uses remote/local data source
- Result comes back and updates the UI state

## 4. Dependency injection (DI)

Dependency injection means instead of creating objects manually inside classes, the app provides them from one central place.

### Why DI is used here

- makes code cleaner
- avoids hard-coded dependencies
- makes testing easier
- helps reuse services like API client, storage, and notifications

### Current implementation

The project uses GetIt through [lib/config/dependency_injection/injection_container.dart](lib/config/dependency_injection/injection_container.dart).

```dart
final sl = GetIt.instance;

Future<void> init() async {
  await registerCore(sl);
  await registerNetwork(sl);
  await registerStorage(sl);
  await registerNotification(sl);
  await registerAuth(sl);
  await registerMap(sl);
  await sl.allReady();
}
```

### How to use it

```dart
final apiService = sl<ApiService>();
final storage = sl<LocalStorageService>();
```

That means you do not need to create these objects everywhere manually.

## 5. API common class

The common network layer is built in:

- [lib/core/network/api_client.dart](lib/core/network/api_client.dart)
- [lib/core/network/api_service.dart](lib/core/network/api_service.dart)
- [lib/core/network/api_interceptor.dart](lib/core/network/api_interceptor.dart)

### What it does

- handles base URL and headers
- checks internet connection before requests
- logs requests and responses
- shows toast errors on failure
- centralizes API calls

### Flow

- UI or repository calls a method from ApiService
- ApiService calls ApiClient
- ApiClient uses Dio to send the request
- response is returned to the repository

### Example

```dart
class ApiService {
  final ApiClient _client;

  ApiService(this._client);

  Future<dynamic> login(Map<String, dynamic> body) =>
      _client.post(ApiEndpoints.login, body);
}
```

This keeps networking logic in one place and avoids repeating HTTP code in every screen.

## 6. Helpers and shared services

These files help the app stay organized:

- [lib/core/utils/logger.dart](lib/core/utils/logger.dart) - logs app events
- [lib/core/services/toast_service.dart](lib/core/services/toast_service.dart) - reusable toasts
- [lib/core/storage](lib/core/storage) - local storage and cache
- [lib/core/navigation](lib/core/navigation) - routing and navigation helpers
- [lib/core/common_widgets](lib/core/common_widgets) - shared UI components
- [lib/core/extensions](lib/core/extensions) - Dart extensions for cleaner code

These helpers reduce duplication and make screens smaller.

## 7. BLoC state management

This app uses Flutter BLoC for managing UI state.

### Basic idea

BLoC works with three parts:

- Event: what happened
- State: what the UI should show
- Bloc: handles business logic and emits new states

### Example from auth flow

- [lib/features/common_features/auth/presentation/bloc/auth_event.dart](lib/features/common_features/auth/presentation/bloc/auth_event.dart)
- [lib/features/common_features/auth/presentation/bloc/auth_state.dart](lib/features/common_features/auth/presentation/bloc/auth_state.dart)
- [lib/features/common_features/auth/presentation/bloc/auth_bloc.dart](lib/features/common_features/auth/presentation/bloc/auth_bloc.dart)

### Flow

1. UI dispatches an event like LoginRequested.
2. Bloc runs logic.
3. Bloc emits Loading, Authenticated, or Error state.
4. UI rebuilds using BlocBuilder or context.read.

### Example

```dart
BlocProvider(
  create: (_) => AuthBloc(...),
  child: LoginScreen(),
);
```

```dart
context.read<AuthBloc>().add(LoginRequested(email, password));
```

### Why BLoC is useful

- keeps UI and logic separate
- makes state predictable
- easier to debug and maintain

## 8. OOP concepts used in this project

Object-Oriented Programming (OOP) is used heavily in this app.

### Simple explanation

- Class: a blueprint
- Object: an instance of a class
- Encapsulation: data and logic stay inside the class
- Inheritance: one class can extend another
- Polymorphism: different classes can share the same interface
- Abstraction: hide implementation details and expose only what is needed

### In this project

- Repository classes implement repository interfaces
- Use cases are small classes with one responsibility
- Services like ApiClient and NotificationService are reusable classes
- BLoC classes manage a specific feature state

Example:

```dart
abstract class AuthRepository {
  Future<AuthEntity> login(String email, String password);
}

class AuthRepositoryImpl implements AuthRepository {
  // implementation here
}
```

This is a strong OOP pattern because the UI depends on the contract, not the concrete implementation.

## 9. How a new feature should be added

A good feature structure is:

1. Create a folder inside [lib/features](lib/features)
2. Add presentation, domain, and data folders
3. Create BLoC, events, states, and UI screens
4. Register dependencies in the DI module
5. Add navigation route if needed

Typical structure:

```text
features/
  your_feature/
    data/
    domain/
    presentation/
```

## 10. Best practices for this project

- Keep widgets small and focused
- Put business logic in use cases or BLoCs
- Use repositories for data access
- Use DI for services and shared dependencies
- Keep API logic inside the network layer
- Reuse common widgets from [lib/core/common_widgets](lib/core/common_widgets)

## 11. Quick learning summary

If you are learning this app, focus on these 4 things first:

- DI: how services are registered and injected
- BLoC: how UI state changes are handled
- OOP: how classes and interfaces are used
- Clean architecture: how the layers communicate

If you want, the next step can be to create a small feature example such as a login flow or a new screen using the same pattern used in this project.
