feat: Migrate staff profile features from Data Connect to V2 REST API
- Removed data_connect package from mobile pubspec.yaml. - Added documentation for V2 profile migration status and QA findings. - Implemented new session management with ClientSessionStore and StaffSessionStore. - Created V2SessionService for handling user sessions via the V2 API. - Developed use cases for cancelling late worker assignments and submitting worker reviews. - Added arguments and use cases for payment chart retrieval and profile completion checks. - Implemented repository interfaces and their implementations for staff main and profile features. - Ensured proper error handling and validation in use cases.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: krow-mobile-architecture
|
||||
description: KROW mobile app Clean Architecture implementation including package structure, dependency rules, feature isolation, BLoC lifecycle management, session handling, and Data Connect connectors pattern. Use this when architecting new mobile features, debugging state management issues, preventing prop drilling, managing BLoC disposal, implementing session stores, or setting up connector repositories. Essential for maintaining architectural integrity across staff and client apps.
|
||||
description: KROW mobile app Clean Architecture implementation including package structure, dependency rules, feature isolation, BLoC lifecycle management, session handling, and V2 REST API integration. Use this when architecting new mobile features, debugging state management issues, preventing prop drilling, managing BLoC disposal, implementing session stores, or setting up API repository patterns. Essential for maintaining architectural integrity across staff and client apps.
|
||||
---
|
||||
|
||||
# KROW Mobile Architecture
|
||||
@@ -13,7 +13,7 @@ This skill defines the authoritative mobile architecture for the KROW platform.
|
||||
- Debugging state management or BLoC lifecycle issues
|
||||
- Preventing prop drilling in UI code
|
||||
- Managing session state and authentication
|
||||
- Implementing Data Connect connector repositories
|
||||
- Implementing V2 API repository patterns
|
||||
- Setting up feature modules and dependency injection
|
||||
- Understanding package boundaries and dependencies
|
||||
- Refactoring legacy code to Clean Architecture
|
||||
@@ -46,13 +46,14 @@ KROW follows **Clean Architecture** in a **Melos Monorepo**. Dependencies flow *
|
||||
│ both depend on
|
||||
┌─────────────────▼───────────────────────────────────────┐
|
||||
│ Services (Interface Adapters) │
|
||||
│ • data_connect: Backend integration, session mgmt │
|
||||
│ • core: Extensions, base classes, utilities │
|
||||
│ • core: API service, session management, device │
|
||||
│ services, utilities, extensions, base classes │
|
||||
└─────────────────┬───────────────────────────────────────┘
|
||||
│ both depend on
|
||||
│ depends on
|
||||
┌─────────────────▼───────────────────────────────────────┐
|
||||
│ Domain (Stable Core) │
|
||||
│ • Entities (immutable data models) │
|
||||
│ • Entities (data models with fromJson/toJson) │
|
||||
│ • Enums (shared enumerations) │
|
||||
│ • Failures (domain-specific errors) │
|
||||
│ • Pure Dart only, zero Flutter dependencies │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
@@ -69,9 +70,9 @@ KROW follows **Clean Architecture** in a **Melos Monorepo**. Dependencies flow *
|
||||
**Responsibilities:**
|
||||
- Initialize Flutter Modular
|
||||
- Assemble features into navigation tree
|
||||
- Inject concrete implementations (from `data_connect`) into features
|
||||
- Inject concrete implementations into features
|
||||
- Configure environment-specific settings (dev/stage/prod)
|
||||
- Initialize session management
|
||||
- Initialize session management via `V2SessionService`
|
||||
|
||||
**Structure:**
|
||||
```
|
||||
@@ -119,21 +120,22 @@ features/staff/profile/
|
||||
**Key Principles:**
|
||||
- **Presentation:** UI Pages and Widgets, BLoCs/Cubits for state
|
||||
- **Application:** Use Cases (business logic orchestration)
|
||||
- **Data:** Repository implementations (backend integration)
|
||||
- **Data:** Repository implementations using `ApiService` with `V2ApiEndpoints`
|
||||
- **Pages as StatelessWidget:** Move state to BLoCs for better performance and testability
|
||||
- **Feature-level domain is optional:** Only needed when the feature has business logic (use cases, validators). Simple features can have just `data/` + `presentation/`.
|
||||
|
||||
**RESTRICTION:** Features MUST NOT import other features. Communication happens via:
|
||||
- Shared domain entities
|
||||
- Session stores (`StaffSessionStore`, `ClientSessionStore`)
|
||||
- Navigation via Modular
|
||||
- Data Connect connector repositories
|
||||
|
||||
### 2.3 Domain (`apps/mobile/packages/domain`)
|
||||
|
||||
**Role:** The stable, pure heart of the system
|
||||
|
||||
**Responsibilities:**
|
||||
- Define **Entities** (immutable data models using Data Classes or Freezed)
|
||||
- Define **Entities** (data models with `fromJson`/`toJson` for V2 API serialization)
|
||||
- Define **Enums** (shared enumerations in `entities/enums/`)
|
||||
- Define **Failures** (domain-specific error types)
|
||||
|
||||
**Structure:**
|
||||
@@ -144,11 +146,17 @@ domain/
|
||||
│ ├── entities/
|
||||
│ │ ├── user.dart
|
||||
│ │ ├── staff.dart
|
||||
│ │ └── shift.dart
|
||||
│ └── failures/
|
||||
│ ├── failure.dart # Base class
|
||||
│ ├── auth_failure.dart
|
||||
│ └── network_failure.dart
|
||||
│ │ ├── shift.dart
|
||||
│ │ └── enums/
|
||||
│ │ ├── staff_status.dart
|
||||
│ │ └── order_type.dart
|
||||
│ ├── failures/
|
||||
│ │ ├── failure.dart # Base class
|
||||
│ │ ├── auth_failure.dart
|
||||
│ │ └── network_failure.dart
|
||||
│ └── core/
|
||||
│ └── services/api_services/
|
||||
│ └── base_api_service.dart
|
||||
└── pubspec.yaml
|
||||
```
|
||||
|
||||
@@ -161,68 +169,120 @@ class Staff extends Equatable {
|
||||
final String name;
|
||||
final String email;
|
||||
final StaffStatus status;
|
||||
|
||||
|
||||
const Staff({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.email,
|
||||
required this.status,
|
||||
});
|
||||
|
||||
|
||||
factory Staff.fromJson(Map<String, dynamic> json) {
|
||||
return Staff(
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
email: json['email'] as String,
|
||||
status: StaffStatus.values.byName(json['status'] as String),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'email': email,
|
||||
'status': status.name,
|
||||
};
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, name, email, status];
|
||||
}
|
||||
```
|
||||
|
||||
**RESTRICTION:**
|
||||
**RESTRICTION:**
|
||||
- NO Flutter dependencies (no `import 'package:flutter/material.dart'`)
|
||||
- NO `json_annotation` or serialization code
|
||||
- Only `equatable` for value equality
|
||||
- Pure Dart only
|
||||
- `fromJson`/`toJson` live directly on entities (no separate DTOs or adapters)
|
||||
|
||||
### 2.4 Data Connect (`apps/mobile/packages/data_connect`)
|
||||
### 2.4 Core (`apps/mobile/packages/core`)
|
||||
|
||||
**Role:** Interface Adapter for Backend Access
|
||||
**Role:** Cross-cutting concerns, API infrastructure, session management, device services, and utilities
|
||||
|
||||
**Responsibilities:**
|
||||
- Centralized connector repositories (see Data Connect Connectors Pattern section)
|
||||
- Implement Firebase Data Connect service layer
|
||||
- Map Domain Entities ↔ Data Connect generated code
|
||||
- Handle Firebase exceptions → domain failures
|
||||
- Provide `DataConnectService` with session management
|
||||
- `ApiService` — HTTP client wrapper around Dio with consistent response/error handling
|
||||
- `V2ApiEndpoints` — All V2 REST API endpoint constants
|
||||
- `DioClient` — Pre-configured Dio with `AuthInterceptor` and `IdempotencyInterceptor`
|
||||
- `AuthInterceptor` — Automatically attaches Firebase Auth ID token to requests
|
||||
- `IdempotencyInterceptor` — Adds `Idempotency-Key` header to POST/PUT/DELETE requests
|
||||
- `ApiErrorHandler` mixin — Maps API errors to domain failures
|
||||
- `SessionHandlerMixin` — Handles auth state, token refresh, role validation
|
||||
- `V2SessionService` — Manages session lifecycle, replaces legacy DataConnectService
|
||||
- Session stores (`StaffSessionStore`, `ClientSessionStore`)
|
||||
- Device services (camera, gallery, location, notifications, storage, etc.)
|
||||
- Extension methods (`NavigationExtensions`, `ListExtensions`, etc.)
|
||||
- Base classes (`UseCase`, `Failure`, `BlocErrorHandler`)
|
||||
- Logger configuration
|
||||
- `AppConfig` — Environment-specific configuration (API base URLs, keys)
|
||||
|
||||
**Structure:**
|
||||
```
|
||||
data_connect/
|
||||
core/
|
||||
├── lib/
|
||||
│ ├── src/
|
||||
│ │ ├── services/
|
||||
│ │ │ ├── data_connect_service.dart # Core service
|
||||
│ │ │ └── mixins/
|
||||
│ │ │ └── session_handler_mixin.dart
|
||||
│ │ ├── connectors/ # Connector pattern (see below)
|
||||
│ │ │ ├── staff/
|
||||
│ │ │ │ ├── domain/
|
||||
│ │ │ │ │ ├── repositories/
|
||||
│ │ │ │ │ │ └── staff_connector_repository.dart
|
||||
│ │ │ │ │ └── usecases/
|
||||
│ │ │ │ │ └── get_profile_completion_usecase.dart
|
||||
│ │ │ │ └── data/
|
||||
│ │ │ │ └── repositories/
|
||||
│ │ │ │ └── staff_connector_repository_impl.dart
|
||||
│ │ │ ├── order/
|
||||
│ │ │ └── shifts/
|
||||
│ │ └── session/
|
||||
│ │ ├── staff_session_store.dart
|
||||
│ │ └── client_session_store.dart
|
||||
│ └── krow_data_connect.dart # Exports
|
||||
│ ├── core.dart # Barrel exports
|
||||
│ └── src/
|
||||
│ ├── config/
|
||||
│ │ ├── app_config.dart # Env-specific config (V2_API_BASE_URL, etc.)
|
||||
│ │ └── app_environment.dart
|
||||
│ ├── services/
|
||||
│ │ ├── api_service/
|
||||
│ │ │ ├── api_service.dart # ApiService (get/post/put/patch/delete)
|
||||
│ │ │ ├── dio_client.dart # Pre-configured Dio
|
||||
│ │ │ ├── inspectors/
|
||||
│ │ │ │ ├── auth_interceptor.dart
|
||||
│ │ │ │ └── idempotency_interceptor.dart
|
||||
│ │ │ ├── mixins/
|
||||
│ │ │ │ ├── api_error_handler.dart
|
||||
│ │ │ │ └── session_handler_mixin.dart
|
||||
│ │ │ └── core_api_services/
|
||||
│ │ │ ├── v2_api_endpoints.dart
|
||||
│ │ │ ├── core_api_endpoints.dart
|
||||
│ │ │ ├── file_upload/
|
||||
│ │ │ ├── signed_url/
|
||||
│ │ │ ├── llm/
|
||||
│ │ │ ├── verification/
|
||||
│ │ │ └── rapid_order/
|
||||
│ │ ├── session/
|
||||
│ │ │ ├── v2_session_service.dart
|
||||
│ │ │ ├── staff_session_store.dart
|
||||
│ │ │ └── client_session_store.dart
|
||||
│ │ └── device/
|
||||
│ │ ├── camera/
|
||||
│ │ ├── gallery/
|
||||
│ │ ├── location/
|
||||
│ │ ├── notification/
|
||||
│ │ ├── storage/
|
||||
│ │ └── background_task/
|
||||
│ ├── presentation/
|
||||
│ │ ├── mixins/
|
||||
│ │ │ └── bloc_error_handler.dart
|
||||
│ │ └── observers/
|
||||
│ │ └── core_bloc_observer.dart
|
||||
│ ├── routing/
|
||||
│ │ └── routing.dart
|
||||
│ ├── domain/
|
||||
│ │ ├── arguments/
|
||||
│ │ └── usecases/
|
||||
│ └── utils/
|
||||
│ ├── date_time_utils.dart
|
||||
│ ├── geo_utils.dart
|
||||
│ └── time_utils.dart
|
||||
└── pubspec.yaml
|
||||
```
|
||||
|
||||
**RESTRICTION:**
|
||||
- NO feature-specific logic
|
||||
- Connectors are domain-neutral and reusable
|
||||
- All queries follow Clean Architecture (domain interfaces → data implementations)
|
||||
- Core services are domain-neutral and reusable
|
||||
- All V2 API access goes through `ApiService` — never use raw Dio directly in features
|
||||
|
||||
### 2.5 Design System (`apps/mobile/packages/design_system`)
|
||||
|
||||
@@ -274,13 +334,13 @@ design_system/
|
||||
|
||||
**Feature Integration:**
|
||||
```dart
|
||||
// ✅ CORRECT: Access via Slang's global `t` accessor
|
||||
// CORRECT: Access via Slang's global `t` accessor
|
||||
import 'package:core_localization/core_localization.dart';
|
||||
|
||||
Text(t.client_create_order.review.invalid_arguments)
|
||||
Text(t.errors.order.creation_failed)
|
||||
|
||||
// ❌ FORBIDDEN: Hardcoded user-facing strings
|
||||
// FORBIDDEN: Hardcoded user-facing strings
|
||||
Text('Invalid review arguments') // Must use localized key
|
||||
Text('Order created!') // Must use localized key
|
||||
```
|
||||
@@ -313,62 +373,86 @@ BlocProvider<LocaleBloc>(
|
||||
)
|
||||
```
|
||||
|
||||
### 2.7 Core (`apps/mobile/packages/core`)
|
||||
|
||||
**Role:** Cross-cutting concerns
|
||||
|
||||
**Responsibilities:**
|
||||
- Extension methods (NavigationExtensions, ListExtensions, etc.)
|
||||
- Base classes (UseCase, Failure, BlocErrorHandler)
|
||||
- Logger configuration
|
||||
- Result types for functional error handling
|
||||
|
||||
## 3. Dependency Direction Rules
|
||||
|
||||
1. **Domain Independence:** `domain` knows NOTHING about outer layers
|
||||
- Defines *what* needs to be done, not *how*
|
||||
- Pure Dart, zero Flutter dependencies
|
||||
- Stable contracts that rarely change
|
||||
- Entities include `fromJson`/`toJson` for practical V2 API serialization
|
||||
|
||||
2. **UI Agnosticism:** Features depend on `design_system` for UI and `domain` for logic
|
||||
- Features do NOT know about Firebase or backend details
|
||||
- Features do NOT know about HTTP/Dio details
|
||||
- Backend changes don't affect feature implementation
|
||||
|
||||
3. **Data Isolation:** `data_connect` depends on `domain` to know interfaces
|
||||
- Implements domain repository interfaces
|
||||
- Maps backend models to domain entities
|
||||
3. **Data Isolation:** Feature `data/` layer depends on `core` for API access and `domain` for entities
|
||||
- RepoImpl uses `ApiService` with `V2ApiEndpoints`
|
||||
- Maps JSON responses to domain entities via `Entity.fromJson()`
|
||||
- Does NOT know about UI
|
||||
|
||||
**Dependency Flow:**
|
||||
```
|
||||
Apps → Features → Design System
|
||||
→ Core Localization
|
||||
→ Data Connect → Domain
|
||||
→ Core
|
||||
→ Core → Domain
|
||||
```
|
||||
|
||||
## 4. Data Connect Service & Session Management
|
||||
## 4. V2 API Service & Session Management
|
||||
|
||||
### 4.1 Session Handler Mixin
|
||||
### 4.1 ApiService
|
||||
|
||||
**Location:** `apps/mobile/packages/data_connect/lib/src/services/mixins/session_handler_mixin.dart`
|
||||
**Location:** `apps/mobile/packages/core/lib/src/services/api_service/api_service.dart`
|
||||
|
||||
**Responsibilities:**
|
||||
- Automatic token refresh (triggered when <5 minutes to expiry)
|
||||
- Firebase auth state listening
|
||||
- Role-based access validation
|
||||
- Session state stream emissions
|
||||
- 3-attempt retry with exponential backoff (1s → 2s → 4s)
|
||||
- Wraps Dio HTTP methods (GET, POST, PUT, PATCH, DELETE)
|
||||
- Consistent response parsing via `ApiResponse`
|
||||
- Consistent error handling (maps `DioException` to `ApiResponse` with V2 error envelope)
|
||||
|
||||
**Key Usage:**
|
||||
```dart
|
||||
final ApiService apiService;
|
||||
|
||||
// GET request
|
||||
final response = await apiService.get(
|
||||
V2ApiEndpoints.staffDashboard,
|
||||
params: {'date': '2026-01-15'},
|
||||
);
|
||||
|
||||
// POST request
|
||||
final response = await apiService.post(
|
||||
V2ApiEndpoints.staffClockIn,
|
||||
data: {'shiftId': shiftId, 'latitude': lat, 'longitude': lng},
|
||||
);
|
||||
```
|
||||
|
||||
### 4.2 DioClient & Interceptors
|
||||
|
||||
**Location:** `apps/mobile/packages/core/lib/src/services/api_service/dio_client.dart`
|
||||
|
||||
**Pre-configured with:**
|
||||
- `AuthInterceptor` — Automatically attaches Firebase Auth ID token as `Bearer` token
|
||||
- `IdempotencyInterceptor` — Adds `Idempotency-Key` (UUID v4) to POST/PUT/DELETE requests
|
||||
- `LogInterceptor` — Logs request/response bodies for debugging
|
||||
|
||||
### 4.3 V2SessionService
|
||||
|
||||
**Location:** `apps/mobile/packages/core/lib/src/services/session/v2_session_service.dart`
|
||||
|
||||
**Responsibilities:**
|
||||
- Manages session lifecycle (initialize, refresh, invalidate)
|
||||
- Fetches session data from V2 API on auth state change
|
||||
- Populates session stores with user/role data
|
||||
- Provides session state stream for `SessionListener`
|
||||
|
||||
**Key Method:**
|
||||
```dart
|
||||
// Call once on app startup
|
||||
DataConnectService.instance.initializeAuthListener(
|
||||
V2SessionService.instance.initializeAuthListener(
|
||||
allowedRoles: ['STAFF', 'BOTH'], // or ['CLIENT', 'BUSINESS', 'BOTH']
|
||||
);
|
||||
```
|
||||
|
||||
### 4.2 Session Listener Widget
|
||||
### 4.4 Session Listener Widget
|
||||
|
||||
**Location:** `apps/mobile/apps/<app>/lib/src/widgets/session_listener.dart`
|
||||
|
||||
@@ -381,13 +465,13 @@ DataConnectService.instance.initializeAuthListener(
|
||||
```dart
|
||||
// main.dart
|
||||
runApp(
|
||||
SessionListener( // ← Critical wrapper
|
||||
SessionListener( // Critical wrapper
|
||||
child: ModularApp(module: AppModule(), child: AppWidget()),
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
### 4.3 Repository Pattern with Data Connect
|
||||
### 4.5 Repository Pattern with V2 API
|
||||
|
||||
**Step 1:** Define interface in feature domain:
|
||||
```dart
|
||||
@@ -397,32 +481,33 @@ abstract interface class ProfileRepositoryInterface {
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2:** Implement using `DataConnectService.run()`:
|
||||
**Step 2:** Implement using `ApiService` with `V2ApiEndpoints`:
|
||||
```dart
|
||||
// features/staff/profile/lib/src/data/repositories_impl/
|
||||
class ProfileRepositoryImpl implements ProfileRepositoryInterface {
|
||||
final DataConnectService _service = DataConnectService.instance;
|
||||
|
||||
final ApiService _apiService;
|
||||
|
||||
ProfileRepositoryImpl({required ApiService apiService})
|
||||
: _apiService = apiService;
|
||||
|
||||
@override
|
||||
Future<Staff> getProfile(String id) async {
|
||||
return await _service.run(() async {
|
||||
final response = await _service.connector
|
||||
.getStaffById(id: id)
|
||||
.execute();
|
||||
return _mapToStaff(response.data.staff);
|
||||
});
|
||||
final response = await _apiService.get(
|
||||
V2ApiEndpoints.staffSession,
|
||||
params: {'staffId': id},
|
||||
);
|
||||
return Staff.fromJson(response.data as Map<String, dynamic>);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits of `_service.run()`:**
|
||||
- ✅ Auto validates user is authenticated
|
||||
- ✅ Refreshes token if <5 min to expiry
|
||||
- ✅ Executes the query
|
||||
- ✅ 3-attempt retry with exponential backoff
|
||||
- ✅ Maps exceptions to domain failures
|
||||
**Benefits of `ApiService` + interceptors:**
|
||||
- AuthInterceptor auto-attaches Firebase Auth token
|
||||
- IdempotencyInterceptor prevents duplicate writes
|
||||
- Consistent error handling via `ApiResponse`
|
||||
- No manual token management in features
|
||||
|
||||
### 4.4 Session Store Pattern
|
||||
### 4.6 Session Store Pattern
|
||||
|
||||
After successful auth, populate session stores:
|
||||
|
||||
@@ -451,9 +536,10 @@ ClientSessionStore.instance.setSession(
|
||||
```dart
|
||||
final session = StaffSessionStore.instance.session;
|
||||
if (session?.staff == null) {
|
||||
final staff = await getStaffById(session!.user.uid);
|
||||
final response = await apiService.get(V2ApiEndpoints.staffSession);
|
||||
final staff = Staff.fromJson(response.data as Map<String, dynamic>);
|
||||
StaffSessionStore.instance.setSession(
|
||||
session.copyWith(staff: staff),
|
||||
session!.copyWith(staff: staff),
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -463,12 +549,12 @@ if (session?.staff == null) {
|
||||
### Zero Direct Imports
|
||||
|
||||
```dart
|
||||
// ❌ FORBIDDEN
|
||||
// FORBIDDEN
|
||||
import 'package:staff_profile/staff_profile.dart'; // in another feature
|
||||
|
||||
// ✅ ALLOWED
|
||||
// ALLOWED
|
||||
import 'package:krow_domain/krow_domain.dart'; // shared domain
|
||||
import 'package:krow_core/krow_core.dart'; // shared utilities
|
||||
import 'package:krow_core/krow_core.dart'; // shared utilities + API
|
||||
import 'package:design_system/design_system.dart'; // shared UI
|
||||
```
|
||||
|
||||
@@ -485,7 +571,7 @@ extension NavigationExtensions on IModularNavigator {
|
||||
await navigate('/home'); // Fallback
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Safely push with fallback to home
|
||||
Future<T?> safePush<T>(String route) async {
|
||||
try {
|
||||
@@ -495,7 +581,7 @@ extension NavigationExtensions on IModularNavigator {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Safely pop with guard against empty stack
|
||||
void popSafe() {
|
||||
if (canPop()) {
|
||||
@@ -512,23 +598,23 @@ extension NavigationExtensions on IModularNavigator {
|
||||
// apps/mobile/apps/staff/lib/src/navigation/staff_navigator.dart
|
||||
extension StaffNavigator on IModularNavigator {
|
||||
Future<void> toStaffHome() => safeNavigate(StaffPaths.home);
|
||||
|
||||
Future<void> toShiftDetails(String shiftId) =>
|
||||
|
||||
Future<void> toShiftDetails(String shiftId) =>
|
||||
safePush('${StaffPaths.shifts}/$shiftId');
|
||||
|
||||
|
||||
Future<void> toProfileEdit() => safePush(StaffPaths.profileEdit);
|
||||
}
|
||||
```
|
||||
|
||||
**Usage in Features:**
|
||||
```dart
|
||||
// ✅ CORRECT
|
||||
// CORRECT
|
||||
Modular.to.toStaffHome();
|
||||
Modular.to.toShiftDetails(shiftId: '123');
|
||||
Modular.to.popSafe();
|
||||
|
||||
// ❌ AVOID
|
||||
Modular.to.navigate('/home'); // No safety
|
||||
// AVOID
|
||||
Modular.to.navigate('/profile'); // No safety
|
||||
Navigator.push(...); // No Modular integration
|
||||
```
|
||||
|
||||
@@ -536,9 +622,9 @@ Navigator.push(...); // No Modular integration
|
||||
|
||||
Features don't share state directly. Use:
|
||||
|
||||
1. **Domain Repositories:** Centralized data sources
|
||||
1. **Domain Repositories:** Centralized data sources via `ApiService`
|
||||
2. **Session Stores:** `StaffSessionStore`, `ClientSessionStore` for app-wide context
|
||||
3. **Event Streams:** If needed, via `DataConnectService` streams
|
||||
3. **Event Streams:** If needed, via `V2SessionService` streams
|
||||
4. **Navigation Arguments:** Pass IDs, not full objects
|
||||
|
||||
## 6. App-Specific Session Management
|
||||
@@ -549,11 +635,11 @@ Features don't share state directly. Use:
|
||||
// main.dart
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
DataConnectService.instance.initializeAuthListener(
|
||||
|
||||
V2SessionService.instance.initializeAuthListener(
|
||||
allowedRoles: ['STAFF', 'BOTH'],
|
||||
);
|
||||
|
||||
|
||||
runApp(
|
||||
SessionListener(
|
||||
child: ModularApp(module: StaffAppModule(), child: StaffApp()),
|
||||
@@ -564,11 +650,11 @@ void main() async {
|
||||
|
||||
**Session Store:** `StaffSessionStore`
|
||||
- Fields: `user`, `staff`, `ownerId`
|
||||
- Lazy load: `getStaffById()` if staff is null
|
||||
- Lazy load: fetch from `V2ApiEndpoints.staffSession` if staff is null
|
||||
|
||||
**Navigation:**
|
||||
- Authenticated → `Modular.to.toStaffHome()`
|
||||
- Unauthenticated → `Modular.to.toInitialPage()`
|
||||
- Authenticated -> `Modular.to.toStaffHome()`
|
||||
- Unauthenticated -> `Modular.to.toInitialPage()`
|
||||
|
||||
### Client App
|
||||
|
||||
@@ -576,11 +662,11 @@ void main() async {
|
||||
// main.dart
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
DataConnectService.instance.initializeAuthListener(
|
||||
|
||||
V2SessionService.instance.initializeAuthListener(
|
||||
allowedRoles: ['CLIENT', 'BUSINESS', 'BOTH'],
|
||||
);
|
||||
|
||||
|
||||
runApp(
|
||||
SessionListener(
|
||||
child: ModularApp(module: ClientAppModule(), child: ClientApp()),
|
||||
@@ -591,137 +677,138 @@ void main() async {
|
||||
|
||||
**Session Store:** `ClientSessionStore`
|
||||
- Fields: `user`, `business`
|
||||
- Lazy load: `getBusinessById()` if business is null
|
||||
- Lazy load: fetch from `V2ApiEndpoints.clientSession` if business is null
|
||||
|
||||
**Navigation:**
|
||||
- Authenticated → `Modular.to.toClientHome()`
|
||||
- Unauthenticated → `Modular.to.toInitialPage()`
|
||||
- Authenticated -> `Modular.to.toClientHome()`
|
||||
- Unauthenticated -> `Modular.to.toInitialPage()`
|
||||
|
||||
## 7. Data Connect Connectors Pattern
|
||||
## 7. V2 API Repository Pattern
|
||||
|
||||
**Problem:** Without connectors, each feature duplicates backend queries.
|
||||
**Problem:** Without a consistent pattern, each feature handles HTTP differently.
|
||||
|
||||
**Solution:** Centralize all backend queries in `data_connect/connectors/`.
|
||||
**Solution:** Feature RepoImpl uses `ApiService` with `V2ApiEndpoints`, returning domain entities via `Entity.fromJson()`.
|
||||
|
||||
### Structure
|
||||
|
||||
Mirror backend connector structure:
|
||||
Repository implementations live in the feature package:
|
||||
|
||||
```
|
||||
data_connect/lib/src/connectors/
|
||||
├── staff/
|
||||
features/staff/profile/
|
||||
├── lib/src/
|
||||
│ ├── domain/
|
||||
│ │ ├── repositories/
|
||||
│ │ │ └── staff_connector_repository.dart # Interface
|
||||
│ │ └── usecases/
|
||||
│ │ └── get_profile_completion_usecase.dart
|
||||
│ └── data/
|
||||
│ └── repositories/
|
||||
│ └── staff_connector_repository_impl.dart # Implementation
|
||||
├── order/
|
||||
├── shifts/
|
||||
└── user/
|
||||
│ │ └── repositories/
|
||||
│ │ └── profile_repository_interface.dart # Interface
|
||||
│ ├── data/
|
||||
│ │ └── repositories_impl/
|
||||
│ │ └── profile_repository_impl.dart # Implementation
|
||||
│ └── presentation/
|
||||
│ └── blocs/
|
||||
│ └── profile_cubit.dart
|
||||
```
|
||||
|
||||
**Maps to backend:**
|
||||
```
|
||||
backend/dataconnect/connector/
|
||||
├── staff/
|
||||
├── order/
|
||||
├── shifts/
|
||||
└── user/
|
||||
```
|
||||
### Repository Interface
|
||||
|
||||
### Clean Architecture in Connectors
|
||||
|
||||
**Domain Interface:**
|
||||
```dart
|
||||
// staff_connector_repository.dart
|
||||
abstract interface class StaffConnectorRepository {
|
||||
Future<bool> getProfileCompletion();
|
||||
Future<Staff> getStaffById(String id);
|
||||
// profile_repository_interface.dart
|
||||
abstract interface class ProfileRepositoryInterface {
|
||||
Future<Staff> getProfile();
|
||||
Future<void> updatePersonalInfo(Map<String, dynamic> data);
|
||||
Future<List<ProfileSection>> getProfileSections();
|
||||
}
|
||||
```
|
||||
|
||||
**Use Case:**
|
||||
```dart
|
||||
// get_profile_completion_usecase.dart
|
||||
class GetProfileCompletionUseCase {
|
||||
final StaffConnectorRepository _repository;
|
||||
|
||||
GetProfileCompletionUseCase({required StaffConnectorRepository repository})
|
||||
: _repository = repository;
|
||||
|
||||
Future<bool> call() => _repository.getProfileCompletion();
|
||||
}
|
||||
```
|
||||
### Repository Implementation
|
||||
|
||||
**Data Implementation:**
|
||||
```dart
|
||||
// staff_connector_repository_impl.dart
|
||||
class StaffConnectorRepositoryImpl implements StaffConnectorRepository {
|
||||
final DataConnectService _service;
|
||||
|
||||
// profile_repository_impl.dart
|
||||
class ProfileRepositoryImpl implements ProfileRepositoryInterface {
|
||||
final ApiService _apiService;
|
||||
|
||||
ProfileRepositoryImpl({required ApiService apiService})
|
||||
: _apiService = apiService;
|
||||
|
||||
@override
|
||||
Future<bool> getProfileCompletion() async {
|
||||
return _service.run(() async {
|
||||
final staffId = await _service.getStaffId();
|
||||
final response = await _service.connector
|
||||
.getStaffProfileCompletion(id: staffId)
|
||||
.execute();
|
||||
|
||||
return _isProfileComplete(response);
|
||||
});
|
||||
Future<Staff> getProfile() async {
|
||||
final response = await _apiService.get(V2ApiEndpoints.staffSession);
|
||||
final data = response.data as Map<String, dynamic>;
|
||||
return Staff.fromJson(data['staff'] as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> updatePersonalInfo(Map<String, dynamic> data) async {
|
||||
await _apiService.put(
|
||||
V2ApiEndpoints.staffPersonalInfo,
|
||||
data: data,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<ProfileSection>> getProfileSections() async {
|
||||
final response = await _apiService.get(V2ApiEndpoints.staffProfileSections);
|
||||
final list = response.data['sections'] as List<dynamic>;
|
||||
return list
|
||||
.map((e) => ProfileSection.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Feature Integration
|
||||
### Feature Module Integration
|
||||
|
||||
**Step 1:** Feature registers connector repository:
|
||||
```dart
|
||||
// staff_main_module.dart
|
||||
class StaffMainModule extends Module {
|
||||
// profile_module.dart
|
||||
class ProfileModule extends Module {
|
||||
@override
|
||||
void binds(Injector i) {
|
||||
i.addLazySingleton<StaffConnectorRepository>(
|
||||
StaffConnectorRepositoryImpl.new,
|
||||
i.addLazySingleton<ProfileRepositoryInterface>(
|
||||
() => ProfileRepositoryImpl(apiService: i.get<ApiService>()),
|
||||
);
|
||||
|
||||
|
||||
i.addLazySingleton(
|
||||
() => GetProfileCompletionUseCase(
|
||||
repository: i.get<StaffConnectorRepository>(),
|
||||
() => GetProfileUseCase(
|
||||
repository: i.get<ProfileRepositoryInterface>(),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
i.addLazySingleton(
|
||||
() => StaffMainCubit(
|
||||
getProfileCompletionUsecase: i.get(),
|
||||
() => ProfileCubit(
|
||||
getProfileUseCase: i.get(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2:** BLoC uses it:
|
||||
### BLoC Usage
|
||||
|
||||
```dart
|
||||
class StaffMainCubit extends Cubit<StaffMainState> {
|
||||
final GetProfileCompletionUseCase _getProfileCompletionUsecase;
|
||||
|
||||
Future<void> loadProfileCompletion() async {
|
||||
final isComplete = await _getProfileCompletionUsecase();
|
||||
emit(state.copyWith(isProfileComplete: isComplete));
|
||||
class ProfileCubit extends Cubit<ProfileState> with BlocErrorHandler<ProfileState> {
|
||||
final GetProfileUseCase _getProfileUseCase;
|
||||
|
||||
Future<void> loadProfile() async {
|
||||
emit(state.copyWith(status: ProfileStatus.loading));
|
||||
|
||||
await handleError(
|
||||
emit: emit,
|
||||
action: () async {
|
||||
final profile = await _getProfileUseCase();
|
||||
emit(state.copyWith(status: ProfileStatus.loaded, profile: profile));
|
||||
},
|
||||
onError: (errorKey) => state.copyWith(status: ProfileStatus.error),
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Benefits
|
||||
|
||||
✅ **No Duplication** - Query implemented once, used by many features
|
||||
✅ **Single Source of Truth** - Backend change → update one place
|
||||
✅ **Reusability** - Any feature can use any connector
|
||||
✅ **Testability** - Mock connector repo to test features
|
||||
✅ **Scalability** - Easy to add connectors as backend grows
|
||||
- **No Duplication** — Endpoint constants defined once in `V2ApiEndpoints`
|
||||
- **Consistent Auth** — `AuthInterceptor` handles token attachment automatically
|
||||
- **Idempotent Writes** — `IdempotencyInterceptor` prevents duplicate mutations
|
||||
- **Domain Purity** — Entities use `fromJson`/`toJson` directly, no mapping layers
|
||||
- **Testability** — Mock `ApiService` to test RepoImpl in isolation
|
||||
- **Scalability** — Add new endpoints to `V2ApiEndpoints`, implement in feature RepoImpl
|
||||
|
||||
## 8. Avoiding Prop Drilling: Direct BLoC Access
|
||||
|
||||
@@ -730,23 +817,23 @@ class StaffMainCubit extends Cubit<StaffMainState> {
|
||||
Passing data through intermediate widgets creates maintenance burden:
|
||||
|
||||
```dart
|
||||
// ❌ BAD: Prop drilling
|
||||
// BAD: Prop drilling
|
||||
ProfilePage(status: status)
|
||||
→ ProfileHeader(status: status)
|
||||
→ ProfileLevelBadge(status: status) // Only widget that needs it
|
||||
-> ProfileHeader(status: status)
|
||||
-> ProfileLevelBadge(status: status) // Only widget that needs it
|
||||
```
|
||||
|
||||
### The Solution: BlocBuilder in Leaf Widgets
|
||||
|
||||
```dart
|
||||
// ✅ GOOD: Direct BLoC access
|
||||
// GOOD: Direct BLoC access
|
||||
class ProfileLevelBadge extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<ProfileCubit, ProfileState>(
|
||||
builder: (context, state) {
|
||||
if (state.profile == null) return const SizedBox.shrink();
|
||||
|
||||
|
||||
final level = _mapStatusToLevel(state.profile!.status);
|
||||
return LevelBadgeUI(level: level);
|
||||
},
|
||||
@@ -765,9 +852,9 @@ class ProfileLevelBadge extends StatelessWidget {
|
||||
**Decision Tree:**
|
||||
```
|
||||
Does this widget need data?
|
||||
├─ YES, leaf widget → Use BlocBuilder
|
||||
├─ YES, container → Use BlocBuilder in child
|
||||
└─ NO → Don't add prop
|
||||
├─ YES, leaf widget -> Use BlocBuilder
|
||||
├─ YES, container -> Use BlocBuilder in child
|
||||
└─ NO -> Don't add prop
|
||||
```
|
||||
|
||||
## 9. BLoC Lifecycle & State Emission Safety
|
||||
@@ -780,7 +867,7 @@ StateError: Cannot emit new states after calling close
|
||||
```
|
||||
|
||||
**Root Causes:**
|
||||
1. Transient BLoCs created with `BlocProvider(create:)` → disposed prematurely
|
||||
1. Transient BLoCs created with `BlocProvider(create:)` -> disposed prematurely
|
||||
2. Multiple BlocProviders disposing same singleton
|
||||
3. User navigates away during async operation
|
||||
|
||||
@@ -789,26 +876,26 @@ StateError: Cannot emit new states after calling close
|
||||
#### Step 1: Register as Singleton
|
||||
|
||||
```dart
|
||||
// ✅ GOOD: Singleton registration
|
||||
// GOOD: Singleton registration
|
||||
i.addLazySingleton<ProfileCubit>(
|
||||
() => ProfileCubit(useCase1, useCase2),
|
||||
);
|
||||
|
||||
// ❌ BAD: Creates new instance each time
|
||||
// BAD: Creates new instance each time
|
||||
i.add(ProfileCubit.new);
|
||||
```
|
||||
|
||||
#### Step 2: Use BlocProvider.value()
|
||||
|
||||
```dart
|
||||
// ✅ GOOD: Reuse singleton
|
||||
// GOOD: Reuse singleton
|
||||
final cubit = Modular.get<ProfileCubit>();
|
||||
BlocProvider<ProfileCubit>.value(
|
||||
value: cubit,
|
||||
child: MyWidget(),
|
||||
)
|
||||
|
||||
// ❌ BAD: Creates duplicate
|
||||
// BAD: Creates duplicate
|
||||
BlocProvider<ProfileCubit>(
|
||||
create: (_) => Modular.get<ProfileCubit>(),
|
||||
child: MyWidget(),
|
||||
@@ -839,13 +926,13 @@ mixin BlocErrorHandler<S> on Cubit<S> {
|
||||
class ProfileCubit extends Cubit<ProfileState> with BlocErrorHandler<ProfileState> {
|
||||
Future<void> loadProfile() async {
|
||||
emit(state.copyWith(status: ProfileStatus.loading));
|
||||
|
||||
|
||||
await handleError(
|
||||
emit: emit,
|
||||
action: () async {
|
||||
final profile = await getProfile();
|
||||
emit(state.copyWith(status: ProfileStatus.loaded, profile: profile));
|
||||
// ✅ Safe even if BLoC disposed
|
||||
// Safe even if BLoC disposed
|
||||
},
|
||||
onError: (errorKey) => state.copyWith(status: ProfileStatus.error),
|
||||
);
|
||||
@@ -863,43 +950,48 @@ class ProfileCubit extends Cubit<ProfileState> with BlocErrorHandler<ProfileStat
|
||||
|
||||
## 10. Anti-Patterns to Avoid
|
||||
|
||||
❌ **Feature imports feature**
|
||||
- **Feature imports feature**
|
||||
```dart
|
||||
import 'package:staff_profile/staff_profile.dart'; // in another feature
|
||||
```
|
||||
|
||||
❌ **Business logic in BLoC**
|
||||
- **Business logic in BLoC**
|
||||
```dart
|
||||
on<LoginRequested>((event, emit) {
|
||||
if (event.email.isEmpty) { // ← Use case responsibility
|
||||
if (event.email.isEmpty) { // Use case responsibility
|
||||
emit(AuthError('Email required'));
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
❌ **Direct Data Connect in features**
|
||||
- **Direct HTTP/Dio in features (use ApiService)**
|
||||
```dart
|
||||
final response = await FirebaseDataConnect.instance.query(); // ← Use repository
|
||||
final response = await Dio().get('https://api.example.com/staff'); // Use ApiService
|
||||
```
|
||||
|
||||
❌ **Global state variables**
|
||||
- **Importing krow_data_connect (deprecated package)**
|
||||
```dart
|
||||
User? currentUser; // ← Use SessionStore
|
||||
import 'package:krow_data_connect/krow_data_connect.dart'; // Use krow_core instead
|
||||
```
|
||||
|
||||
❌ **Direct Navigator.push**
|
||||
- **Global state variables**
|
||||
```dart
|
||||
Navigator.push(context, MaterialPageRoute(...)); // ← Use Modular
|
||||
User? currentUser; // Use SessionStore
|
||||
```
|
||||
|
||||
❌ **Hardcoded navigation**
|
||||
- **Direct Navigator.push**
|
||||
```dart
|
||||
Modular.to.navigate('/profile'); // ← Use safe extensions
|
||||
Navigator.push(context, MaterialPageRoute(...)); // Use Modular
|
||||
```
|
||||
|
||||
❌ **Hardcoded user-facing strings**
|
||||
- **Hardcoded navigation**
|
||||
```dart
|
||||
Text('Order created successfully!'); // ← Use t.section.key from core_localization
|
||||
Modular.to.navigate('/profile'); // Use safe extensions
|
||||
```
|
||||
|
||||
- **Hardcoded user-facing strings**
|
||||
```dart
|
||||
Text('Order created successfully!'); // Use t.section.key from core_localization
|
||||
```
|
||||
|
||||
## Summary
|
||||
@@ -907,17 +999,20 @@ Text('Order created successfully!'); // ← Use t.section.key from core_localiz
|
||||
The architecture enforces:
|
||||
- **Clean Architecture** with strict layer boundaries
|
||||
- **Feature Isolation** via zero cross-feature imports
|
||||
- **Session Management** via DataConnectService and SessionListener
|
||||
- **Connector Pattern** for reusable backend queries
|
||||
- **V2 REST API** integration via `ApiService`, `V2ApiEndpoints`, and interceptors
|
||||
- **Session Management** via `V2SessionService`, session stores, and `SessionListener`
|
||||
- **Repository Pattern** with feature-local RepoImpl using `ApiService`
|
||||
- **BLoC Lifecycle** safety with singletons and safe emit
|
||||
- **Navigation Safety** with typed navigators and fallbacks
|
||||
|
||||
When implementing features:
|
||||
1. Follow package structure strictly
|
||||
2. Use connector repositories for backend access
|
||||
3. Register BLoCs as singletons with `.value()`
|
||||
4. Use safe navigation extensions
|
||||
5. Avoid prop drilling with direct BLoC access
|
||||
6. Keep domain pure and stable
|
||||
2. Use `ApiService` with `V2ApiEndpoints` for all backend access
|
||||
3. Domain entities use `fromJson`/`toJson` for V2 API serialization
|
||||
4. RepoImpl lives in the feature `data/` layer, not a shared package
|
||||
5. Register BLoCs as singletons with `.value()`
|
||||
6. Use safe navigation extensions
|
||||
7. Avoid prop drilling with direct BLoC access
|
||||
8. Keep domain pure and stable
|
||||
|
||||
Architecture is not negotiable. When in doubt, refer to existing well-structured features or ask for clarification.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: krow-mobile-development-rules
|
||||
description: Enforce KROW mobile app development standards including file structure, naming conventions, logic placement boundaries, localization, Data Connect integration, and prototype migration rules. Use this skill whenever working on KROW Flutter mobile features, creating new packages, implementing BLoCs, integrating with backend, or migrating from prototypes. Critical for maintaining clean architecture and preventing architectural degradation.
|
||||
description: Enforce KROW mobile app development standards including file structure, naming conventions, logic placement boundaries, localization, V2 REST API integration, and prototype migration rules. Use this skill whenever working on KROW Flutter mobile features, creating new packages, implementing BLoCs, integrating with backend, or migrating from prototypes. Critical for maintaining clean architecture and preventing architectural degradation.
|
||||
---
|
||||
|
||||
# KROW Mobile Development Rules
|
||||
@@ -11,7 +11,7 @@ These rules are **NON-NEGOTIABLE** enforcement guidelines for the KROW mobile ap
|
||||
|
||||
- Creating new mobile features or packages
|
||||
- Implementing BLoCs, Use Cases, or Repositories
|
||||
- Integrating with Firebase Data Connect backend
|
||||
- Integrating with V2 REST API backend
|
||||
- Migrating code from prototypes
|
||||
- Reviewing mobile code for compliance
|
||||
- Setting up new feature modules
|
||||
@@ -186,15 +186,17 @@ class _LoginPageState extends State<LoginPage> {
|
||||
```dart
|
||||
// profile_repository_impl.dart
|
||||
class ProfileRepositoryImpl implements ProfileRepositoryInterface {
|
||||
ProfileRepositoryImpl({required BaseApiService apiService})
|
||||
: _apiService = apiService;
|
||||
final BaseApiService _apiService;
|
||||
|
||||
@override
|
||||
Future<Staff> getProfile(String id) async {
|
||||
final response = await dataConnect.getStaffById(id: id).execute();
|
||||
// Data transformation happens here
|
||||
return Staff(
|
||||
id: response.data.staff.id,
|
||||
name: response.data.staff.name,
|
||||
// Map Data Connect model to Domain entity
|
||||
final ApiResponse response = await _apiService.get(
|
||||
V2ApiEndpoints.staffProfile(id),
|
||||
);
|
||||
// Data transformation happens here
|
||||
return Staff.fromJson(response.data as Map<String, dynamic>);
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -252,19 +254,19 @@ Modular.to.pop(); // ← Can crash if stack is empty
|
||||
|
||||
**PATTERN:** All navigation MUST have fallback to Home page. Safe extensions automatically handle this.
|
||||
|
||||
### Session Management → DataConnectService + SessionHandlerMixin
|
||||
### Session Management → V2SessionService + SessionHandlerMixin
|
||||
|
||||
**✅ CORRECT:**
|
||||
```dart
|
||||
// In main.dart:
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
|
||||
// Initialize session listener (pick allowed roles for app)
|
||||
DataConnectService.instance.initializeAuthListener(
|
||||
V2SessionService.instance.initializeAuthListener(
|
||||
allowedRoles: ['STAFF', 'BOTH'], // for staff app
|
||||
);
|
||||
|
||||
|
||||
runApp(
|
||||
SessionListener( // Wraps entire app
|
||||
child: ModularApp(module: AppModule(), child: AppWidget()),
|
||||
@@ -274,28 +276,24 @@ void main() async {
|
||||
|
||||
// In repository:
|
||||
class ProfileRepositoryImpl implements ProfileRepositoryInterface {
|
||||
final DataConnectService _service = DataConnectService.instance;
|
||||
|
||||
ProfileRepositoryImpl({required BaseApiService apiService})
|
||||
: _apiService = apiService;
|
||||
final BaseApiService _apiService;
|
||||
|
||||
@override
|
||||
Future<Staff> getProfile(String id) async {
|
||||
// _service.run() handles:
|
||||
// - Auth validation
|
||||
// - Token refresh (if <5 min to expiry)
|
||||
// - Error handling with 3 retries
|
||||
return await _service.run(() async {
|
||||
final response = await _service.connector
|
||||
.getStaffById(id: id)
|
||||
.execute();
|
||||
return _mapToStaff(response.data.staff);
|
||||
});
|
||||
final ApiResponse response = await _apiService.get(
|
||||
V2ApiEndpoints.staffProfile(id),
|
||||
);
|
||||
return Staff.fromJson(response.data as Map<String, dynamic>);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**PATTERN:**
|
||||
- **SessionListener** widget wraps app and shows dialogs for session errors
|
||||
- **SessionHandlerMixin** in `DataConnectService` provides automatic token refresh
|
||||
- **3-attempt retry logic** with exponential backoff (1s → 2s → 4s)
|
||||
- **V2SessionService** provides automatic token refresh and auth management
|
||||
- **ApiService** handles HTTP requests with automatic auth headers
|
||||
- **Role validation** configurable per app
|
||||
|
||||
## 4. Localization Integration (core_localization)
|
||||
@@ -372,7 +370,7 @@ class AppModule extends Module {
|
||||
@override
|
||||
List<Module> get imports => [
|
||||
LocalizationModule(), // ← Required
|
||||
DataConnectModule(),
|
||||
CoreModule(),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -387,44 +385,51 @@ runApp(
|
||||
);
|
||||
```
|
||||
|
||||
## 5. Data Connect Integration
|
||||
## 5. V2 API Integration
|
||||
|
||||
All backend access goes through `DataConnectService`.
|
||||
All backend access goes through `ApiService` with `V2ApiEndpoints`.
|
||||
|
||||
### Repository Pattern
|
||||
|
||||
**Step 1:** Define interface in feature domain:
|
||||
**Step 1:** Define interface in feature domain (optional — feature-level domain layer is optional if entities from `krow_domain` suffice):
|
||||
```dart
|
||||
// domain/repositories/profile_repository_interface.dart
|
||||
abstract interface class ProfileRepositoryInterface {
|
||||
Future<Staff> getProfile(String id);
|
||||
Future<bool> updateProfile(Staff profile);
|
||||
// domain/repositories/shifts_repository_interface.dart
|
||||
abstract interface class ShiftsRepositoryInterface {
|
||||
Future<List<AssignedShift>> getAssignedShifts();
|
||||
Future<AssignedShift> getShiftById(String id);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2:** Implement using `DataConnectService.run()`:
|
||||
**Step 2:** Implement using `ApiService` + `V2ApiEndpoints`:
|
||||
```dart
|
||||
// data/repositories_impl/profile_repository_impl.dart
|
||||
class ProfileRepositoryImpl implements ProfileRepositoryInterface {
|
||||
final DataConnectService _service = DataConnectService.instance;
|
||||
|
||||
// data/repositories_impl/shifts_repository_impl.dart
|
||||
class ShiftsRepositoryImpl implements ShiftsRepositoryInterface {
|
||||
ShiftsRepositoryImpl({required BaseApiService apiService})
|
||||
: _apiService = apiService;
|
||||
final BaseApiService _apiService;
|
||||
|
||||
@override
|
||||
Future<Staff> getProfile(String id) async {
|
||||
return await _service.run(() async {
|
||||
final response = await _service.connector
|
||||
.getStaffById(id: id)
|
||||
.execute();
|
||||
return _mapToStaff(response.data.staff);
|
||||
});
|
||||
Future<List<AssignedShift>> getAssignedShifts() async {
|
||||
final ApiResponse response = await _apiService.get(V2ApiEndpoints.staffShiftsAssigned);
|
||||
final List<dynamic> items = response.data['items'] as List<dynamic>;
|
||||
return items.map((dynamic json) => AssignedShift.fromJson(json as Map<String, dynamic>)).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<AssignedShift> getShiftById(String id) async {
|
||||
final ApiResponse response = await _apiService.get(V2ApiEndpoints.staffShift(id));
|
||||
return AssignedShift.fromJson(response.data as Map<String, dynamic>);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits of `_service.run()`:**
|
||||
- ✅ Automatic auth validation
|
||||
- ✅ Token refresh if needed
|
||||
- ✅ 3-attempt retry with exponential backoff
|
||||
- ✅ Consistent error handling
|
||||
### Key Conventions
|
||||
|
||||
- **Domain entities** have `fromJson` / `toJson` factory methods for serialization
|
||||
- **Status fields** use enums from `krow_domain` (e.g., `ShiftStatus`, `OrderStatus`)
|
||||
- **Money** is represented in cents as `int` (never `double`)
|
||||
- **Timestamps** are `DateTime` objects (parsed from ISO 8601 strings)
|
||||
- **Feature-level domain layer** is optional when `krow_domain` entities cover the need
|
||||
|
||||
### Session Store Pattern
|
||||
|
||||
@@ -448,7 +453,7 @@ ClientSessionStore.instance.setSession(
|
||||
);
|
||||
```
|
||||
|
||||
**Lazy Loading:** If session is null, fetch via `getStaffById()` or `getBusinessById()` and update store.
|
||||
**Lazy Loading:** If session is null, fetch via the appropriate `ApiService.get()` endpoint and update store.
|
||||
|
||||
## 6. Prototype Migration Rules
|
||||
|
||||
@@ -462,7 +467,7 @@ When migrating from `prototypes/`:
|
||||
### ❌ MUST REJECT & REFACTOR
|
||||
- `GetX`, `Provider`, or `MVC` patterns
|
||||
- Any state management not using BLoC
|
||||
- Direct HTTP calls (must use Data Connect)
|
||||
- Direct HTTP calls (must use ApiService with V2ApiEndpoints)
|
||||
- Hardcoded colors/typography (must use design system)
|
||||
- Global state variables
|
||||
- Navigation without Modular
|
||||
@@ -491,13 +496,12 @@ If requirements are unclear:
|
||||
|
||||
### DO NOT
|
||||
- Add 3rd party packages without checking `apps/mobile/packages/core` first
|
||||
- Add `firebase_auth` or `firebase_data_connect` to Feature packages (they belong in `data_connect` only)
|
||||
- Use `addSingleton` for BLoCs (always use `add` method in Modular)
|
||||
- Add `firebase_auth` or `firebase_data_connect` to Feature packages (they belong in `core` only)
|
||||
|
||||
### DO
|
||||
- Use `DataConnectService.instance` for backend operations
|
||||
- Use `ApiService` with `V2ApiEndpoints` for backend operations
|
||||
- Use Flutter Modular for dependency injection
|
||||
- Register BLoCs with `i.addSingleton<CubitType>(() => CubitType(...))`
|
||||
- Register BLoCs with `i.add<CubitType>(() => CubitType(...))` (transient)
|
||||
- Register Use Cases as factories or singletons as needed
|
||||
|
||||
## 9. Error Handling Pattern
|
||||
@@ -516,15 +520,12 @@ class InvalidCredentialsFailure extends AuthFailure {
|
||||
|
||||
### Repository Error Mapping
|
||||
```dart
|
||||
// Map Data Connect exceptions to Domain failures
|
||||
// Map API errors to Domain failures using ApiErrorHandler
|
||||
try {
|
||||
final response = await dataConnect.query();
|
||||
return Right(response);
|
||||
} on DataConnectException catch (e) {
|
||||
if (e.message.contains('unauthorized')) {
|
||||
return Left(InvalidCredentialsFailure());
|
||||
}
|
||||
return Left(ServerFailure(e.message));
|
||||
final response = await _apiService.get(V2ApiEndpoints.staffProfile(id));
|
||||
return Right(Staff.fromJson(response.data as Map<String, dynamic>));
|
||||
} catch (e) {
|
||||
return Left(ApiErrorHandler.mapToFailure(e));
|
||||
}
|
||||
```
|
||||
|
||||
@@ -579,7 +580,7 @@ testWidgets('shows loading indicator when logging in', (tester) async {
|
||||
```
|
||||
|
||||
### Integration Tests
|
||||
- Test full feature flows end-to-end with Data Connect
|
||||
- Test full feature flows end-to-end with V2 API
|
||||
- Use dependency injection to swap implementations if needed
|
||||
|
||||
## 11. Clean Code Principles
|
||||
@@ -635,12 +636,12 @@ Before merging any mobile feature code:
|
||||
- [ ] Zero analyzer warnings
|
||||
|
||||
### Integration
|
||||
- [ ] Data Connect queries via `_service.run()`
|
||||
- [ ] V2 API calls via `ApiService` + `V2ApiEndpoints`
|
||||
- [ ] Error handling with domain failures
|
||||
- [ ] Proper dependency injection in modules
|
||||
|
||||
## Summary
|
||||
|
||||
The key principle: **Clean Architecture with zero tolerance for violations.** Business logic in Use Cases, state in BLoCs, data access in Repositories, UI in Widgets. Features are isolated, backend is centralized, localization is mandatory, and design system is immutable.
|
||||
The key principle: **Clean Architecture with zero tolerance for violations.** Business logic in Use Cases, state in BLoCs, data access in Repositories (via `ApiService` + `V2ApiEndpoints`), UI in Widgets. Features are isolated, backend access is centralized through the V2 REST API layer, localization is mandatory, and design system is immutable.
|
||||
|
||||
When in doubt, refer to existing features following these patterns or ask for clarification. It's better to ask than to introduce architectural debt.
|
||||
|
||||
Reference in New Issue
Block a user