Files
worker/HIVE_MODELS_REFERENCE.md
2025-10-24 11:31:48 +07:00

424 lines
13 KiB
Markdown

# Hive CE Data Models Reference
This document provides a complete reference for all Hive CE data models in the Worker app, mapped to the database schema.
## Summary of Created Models
### ✅ Completed Models
1. **UserModel** (`lib/features/auth/data/models/user_model.dart`) - Type ID: 0
2. **UserSessionModel** (`lib/features/auth/data/models/user_session_model.dart`) - Type ID: 1
3. **ProductModel** (`lib/features/products/data/models/product_model.dart`) - Type ID: 2
4. **StockLevelModel** (`lib/features/products/data/models/stock_level_model.dart`) - Type ID: 3
### 📋 Models To Be Created
The following model files need to be created following the same pattern:
#### Cart Models
- `lib/features/cart/data/models/cart_model.dart` - Type ID: 4
- `lib/features/cart/data/models/cart_item_model.dart` - Type ID: 5
#### Order Models
- `lib/features/orders/data/models/order_model.dart` - Type ID: 6
- `lib/features/orders/data/models/order_item_model.dart` - Type ID: 7
- `lib/features/orders/data/models/invoice_model.dart` - Type ID: 8
- `lib/features/orders/data/models/payment_line_model.dart` - Type ID: 9
#### Loyalty Models
- `lib/features/loyalty/data/models/loyalty_point_entry_model.dart` - Type ID: 10
- `lib/features/loyalty/data/models/gift_catalog_model.dart` - Type ID: 11
- `lib/features/loyalty/data/models/redeemed_gift_model.dart` - Type ID: 12
- `lib/features/loyalty/data/models/points_record_model.dart` - Type ID: 13
#### Project Models
- `lib/features/projects/data/models/project_submission_model.dart` - Type ID: 14
- `lib/features/projects/data/models/design_request_model.dart` - Type ID: 15
#### Quote Models
- `lib/features/quotes/data/models/quote_model.dart` - Type ID: 16
- `lib/features/quotes/data/models/quote_item_model.dart` - Type ID: 17
#### Chat Models
- `lib/features/chat/data/models/chat_room_model.dart` - Type ID: 18
- `lib/features/chat/data/models/message_model.dart` - Type ID: 19
#### Other Models
- `lib/features/notifications/data/models/notification_model.dart` - Type ID: 20
- `lib/features/showrooms/data/models/showroom_model.dart` - Type ID: 21
- `lib/features/showrooms/data/models/showroom_product_model.dart` - Type ID: 22
- `lib/features/account/data/models/payment_reminder_model.dart` - Type ID: 23
- `lib/features/account/data/models/audit_log_model.dart` - Type ID: 24
## Model Template
Each Hive model should follow this structure:
```dart
import 'dart:convert';
import 'package:hive_ce/hive.dart';
import 'package:worker/core/constants/storage_constants.dart';
import 'package:worker/core/database/models/enums.dart'; // If using enums
part 'model_name.g.dart';
/// Model Name
///
/// Hive CE model for caching [entity] data locally.
/// Maps to the '[table_name]' table in the database.
///
/// Type ID: [X]
@HiveType(typeId: HiveTypeIds.modelName)
class ModelName extends HiveObject {
ModelName({
required this.id,
required this.field1,
this.field2,
// ... other fields
});
/// Primary key
@HiveField(0)
final String id;
/// Field description
@HiveField(1)
final String field1;
/// Optional field description
@HiveField(2)
final String? field2;
// Add @HiveField for each database column with sequential numbering
// =========================================================================
// JSON SERIALIZATION
// =========================================================================
factory ModelName.fromJson(Map<String, dynamic> json) {
return ModelName(
id: json['id'] as String,
field1: json['field_1'] as String,
field2: json['field_2'] as String?,
// Map all fields from JSON (snake_case keys)
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'field_1': field1,
'field_2': field2,
// Map all fields to JSON (snake_case keys)
};
}
// =========================================================================
// HELPER METHODS
// =========================================================================
// Add helper methods for:
// - Parsing JSONB fields (use jsonEncode/jsonDecode)
// - Computed properties
// - Validation checks
// - Formatting methods
// =========================================================================
// COPY WITH
// =========================================================================
ModelName copyWith({
String? id,
String? field1,
String? field2,
}) {
return ModelName(
id: id ?? this.id,
field1: field1 ?? this.field1,
field2: field2 ?? this.field2,
);
}
@override
String toString() {
return 'ModelName(id: $id, field1: $field1)';
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is ModelName && other.id == id;
}
@override
int get hashCode => id.hashCode;
}
```
## Important Notes
### JSONB Field Handling
For JSONB fields in the database, store as String in Hive using `jsonEncode`:
```dart
// In model:
@HiveField(X)
final String? jsonbField;
// In fromJson:
jsonbField: json['jsonb_field'] != null
? jsonEncode(json['jsonb_field'])
: null,
// In toJson:
'jsonb_field': jsonbField != null ? jsonDecode(jsonbField!) : null,
// Helper method:
Map<String, dynamic>? get jsonbFieldMap {
if (jsonbField == null) return null;
try {
return jsonDecode(jsonbField!) as Map<String, dynamic>;
} catch (e) {
return null;
}
}
```
### Enum Handling
Use the enums defined in `lib/core/database/models/enums.dart`:
```dart
// In model:
@HiveField(X)
final OrderStatus status;
// In fromJson:
status: OrderStatus.values.firstWhere(
(e) => e.name == (json['status'] as String),
orElse: () => OrderStatus.pending,
),
// In toJson:
'status': status.name,
```
### DateTime Handling
Hive CE supports DateTime natively:
```dart
// In model:
@HiveField(X)
final DateTime createdAt;
@HiveField(Y)
final DateTime? updatedAt;
// In fromJson:
createdAt: DateTime.parse(json['created_at'] as String),
updatedAt: json['updated_at'] != null
? DateTime.parse(json['updated_at'] as String)
: null,
// In toJson:
'created_at': createdAt.toIso8601String(),
'updated_at': updatedAt?.toIso8601String(),
```
### Numeric Fields
Handle numeric precision:
```dart
// For numeric(12,2) fields:
@HiveField(X)
final double amount;
// In fromJson:
amount: (json['amount'] as num).toDouble(),
```
### Array Fields (Lists)
For JSONB arrays, store as JSON string:
```dart
// In model:
@HiveField(X)
final String? participants; // JSONB array
// Helper:
List<String>? get participantsList {
if (participants == null) return null;
try {
final decoded = jsonDecode(participants!) as List;
return decoded.map((e) => e.toString()).toList();
} catch (e) {
return null;
}
}
```
## Database Table to Model Mapping
| Table Name | Model Name | Type ID | Feature | Status |
|------------|------------|---------|---------|--------|
| users | UserModel | 0 | auth | ✅ Created |
| user_sessions | UserSessionModel | 1 | auth | ✅ Created |
| products | ProductModel | 2 | products | ✅ Created |
| stock_levels | StockLevelModel | 3 | products | ✅ Created |
| carts | CartModel | 4 | cart | 📋 To Do |
| cart_items | CartItemModel | 5 | cart | 📋 To Do |
| orders | OrderModel | 6 | orders | 📋 To Do |
| order_items | OrderItemModel | 7 | orders | 📋 To Do |
| invoices | InvoiceModel | 8 | orders | 📋 To Do |
| payment_lines | PaymentLineModel | 9 | orders | 📋 To Do |
| loyalty_point_entries | LoyaltyPointEntryModel | 10 | loyalty | 📋 To Do |
| gift_catalog | GiftCatalogModel | 11 | loyalty | 📋 To Do |
| redeemed_gifts | RedeemedGiftModel | 12 | loyalty | 📋 To Do |
| points_records | PointsRecordModel | 13 | loyalty | 📋 To Do |
| project_submissions | ProjectSubmissionModel | 14 | projects | 📋 To Do |
| design_requests | DesignRequestModel | 15 | projects | 📋 To Do |
| quotes | QuoteModel | 16 | quotes | 📋 To Do |
| quote_items | QuoteItemModel | 17 | quotes | 📋 To Do |
| chat_rooms | ChatRoomModel | 18 | chat | 📋 To Do |
| chat_messages | MessageModel | 19 | chat | 📋 To Do |
| notifications | NotificationModel | 20 | notifications | 📋 To Do |
| showrooms | ShowroomModel | 21 | showrooms | 📋 To Do |
| showroom_products | ShowroomProductModel | 22 | showrooms | 📋 To Do |
| payment_reminders | PaymentReminderModel | 23 | account | 📋 To Do |
| audit_logs | AuditLogModel | 24 | account | 📋 To Do |
## Enum Type IDs (30-59)
All enum types are defined in `lib/core/database/models/enums.dart`:
| Enum Name | Type ID | Values |
|-----------|---------|--------|
| UserRole | 30 | customer, distributor, admin, staff |
| UserStatus | 31 | active, inactive, suspended, pending |
| LoyaltyTier | 32 | bronze, silver, gold, platinum, diamond, titan |
| OrderStatus | 33 | draft, pending, confirmed, processing, shipped, delivered, completed, cancelled, refunded |
| InvoiceType | 34 | sales, proforma, creditNote, debitNote |
| InvoiceStatus | 35 | draft, issued, partiallyPaid, paid, overdue, cancelled, refunded |
| PaymentMethod | 36 | cash, bankTransfer, creditCard, debitCard, eWallet, cheque, creditTerm |
| PaymentStatus | 37 | pending, processing, completed, failed, refunded, cancelled |
| EntryType | 38 | earn, redeem, adjustment, expiry, refund |
| EntrySource | 39 | purchase, referral, promotion, bonus, giftRedemption, projectSubmission, pointsRecord, manualAdjustment |
| ComplaintStatus | 40 | none, pending, investigating, resolved, rejected |
| GiftCategory | 41 | voucher, product, service, discount, experience |
| GiftStatus | 42 | active, used, expired, cancelled |
| PointsStatus | 43 | pending, approved, rejected |
| ProjectType | 44 | residential, commercial, industrial, infrastructure, renovation, interior, exterior |
| SubmissionStatus | 45 | pending, reviewing, approved, rejected, needsRevision |
| DesignStatus | 46 | pending, assigned, inProgress, reviewing, completed, cancelled, onHold |
| QuoteStatus | 47 | draft, sent, viewed, accepted, rejected, expired, converted, cancelled |
| RoomType | 48 | support, sales, orderInquiry, quoteDiscussion, general |
| ContentType | 49 | text, image, file, video, audio, productReference, orderReference, quoteReference |
| ReminderType | 50 | beforeDue, dueDate, overdue, final |
## Code Generation
After creating all models, run the Hive code generator:
```bash
# Generate adapter files for all models
dart run build_runner build --delete-conflicting-outputs
# OR watch for changes
dart run build_runner watch --delete-conflicting-outputs
```
This will generate `.g.dart` files for all models with the `@HiveType` annotation.
## Hive Box Registration
Register all type adapters in the main initialization:
```dart
// In lib/core/database/hive_service.dart or similar
Future<void> initializeHive() async {
await Hive.initFlutter();
// Register enum adapters
Hive.registerAdapter(UserRoleAdapter());
Hive.registerAdapter(UserStatusAdapter());
Hive.registerAdapter(LoyaltyTierAdapter());
Hive.registerAdapter(OrderStatusAdapter());
// ... register all enum adapters
// Register model adapters
Hive.registerAdapter(UserModelAdapter());
Hive.registerAdapter(UserSessionModelAdapter());
Hive.registerAdapter(ProductModelAdapter());
Hive.registerAdapter(StockLevelModelAdapter());
// ... register all model adapters
// Open boxes
await Hive.openBox(HiveBoxNames.userBox);
await Hive.openBox(HiveBoxNames.productBox);
await Hive.openBox(HiveBoxNames.cartBox);
// ... open all boxes
}
```
## Next Steps
1. Create all remaining model files following the template above
2. Ensure all typeIds are unique and match HiveTypeIds constants
3. Run code generation: `dart run build_runner build --delete-conflicting-outputs`
4. Register all adapters in Hive initialization
5. Test model serialization/deserialization
6. Create datasource implementations to use these models
## File Paths Reference
```
lib/features/
├── auth/data/models/
│ ├── user_model.dart ✅
│ └── user_session_model.dart ✅
├── products/data/models/
│ ├── product_model.dart ✅
│ └── stock_level_model.dart ✅
├── cart/data/models/
│ ├── cart_model.dart 📋
│ └── cart_item_model.dart 📋
├── orders/data/models/
│ ├── order_model.dart 📋
│ ├── order_item_model.dart 📋
│ ├── invoice_model.dart 📋
│ └── payment_line_model.dart 📋
├── loyalty/data/models/
│ ├── loyalty_point_entry_model.dart 📋
│ ├── gift_catalog_model.dart 📋
│ ├── redeemed_gift_model.dart 📋
│ └── points_record_model.dart 📋
├── projects/data/models/
│ ├── project_submission_model.dart 📋
│ └── design_request_model.dart 📋
├── quotes/data/models/
│ ├── quote_model.dart 📋
│ └── quote_item_model.dart 📋
├── chat/data/models/
│ ├── chat_room_model.dart 📋
│ └── message_model.dart 📋
├── notifications/data/models/
│ └── notification_model.dart 📋
├── showrooms/data/models/
│ ├── showroom_model.dart 📋
│ └── showroom_product_model.dart 📋
└── account/data/models/
├── payment_reminder_model.dart 📋
└── audit_log_model.dart 📋
```
---
**Legend:**
- ✅ Created and complete
- 📋 To be created following the template