Files
worker/CLAUDE.md
2025-12-01 11:31:26 +07:00

1122 lines
36 KiB
Markdown

# Flutter Mobile App - Worker (EuroTile & Vasta Stone) Expert Guidelines
## 🎯 App Overview
A Flutter-based mobile application designed for contractors, distributors, architects, and brokers in the tile, interior, and construction industry. The app combines a powerful loyalty program with convenient ordering tools and project management capabilities.
### 🎯 Main Objectives:
- Powerful loyalty platform with rewards and membership tiers (Diamond/Platinum/Gold)
- Quick and efficient product ordering system
- Project, contract, and quote management
- Integration with promotions and special offers
- Real-time chat support
### 👥 Target Users:
- **Contractors (Thầu thợ)**: Construction project managers
- **Architects (Kiến trúc sư)**: Design professionals
- **Distributors (Đại lý phân phối)**: Product resellers
- **Real estate brokers (Môi giới)**: Real estate and construction brokers
### 📁 Reference Materials:
The `html/` folder contains UI/UX reference mockups that show the desired design and flow. These HTML files serve as design specifications for the Flutter implementation.
### 📝 Code Examples:
All Dart code examples, patterns, and snippets are maintained in **CODE_EXAMPLES.md**. Refer to that document for:
- Best practices (Hive, AppBar standardization)
- UI/UX components (colors, typography, specs)
- State management patterns
- Performance optimization
- Offline strategies
- Localization setup
- Deployment configurations
### 🎨 App Settings & Theme:
See **[APP_SETTINGS.md](APP_SETTINGS.md)** for:
- AppSettingsBox (Hive) - centralized app settings storage
- Theme system with dynamic seed colors
- ColorScheme usage guide
- Available seed color options
---
## 🤖 SUBAGENT DELEGATION SYSTEM 🤖
**CRITICAL: BE PROACTIVE WITH SUBAGENTS! YOU HAVE SPECIALIZED EXPERTS AVAILABLE!**
### 🚨 DELEGATION MINDSET
**Instead of thinking "I'll handle this myself"** **Think: "Which specialist is BEST suited for this task?"**
### 📋 AVAILABLE SPECIALISTS
You have access to these expert subagents - USE THEM PROACTIVELY:
#### 🎨 **flutter-widget-expert**
- **MUST BE USED for**: Loyalty cards, member cards, product grids, order cards, project cards, chat UI, form layouts, bottom navigation
- **Triggers**: "create widget", "build UI", "card design", "layout", "animation", "custom widget", "loyalty card", "member card"
#### 📊 **riverpod-expert**
- **MUST BE USED for**: Cart state, authentication state, loyalty points state, product state, order state, project state
- **Triggers**: "state management", "provider", "riverpod", "async state", "data flow", "cart", "auth state"
#### 🗄️ **hive-expert**
- **MUST BE USED for**: Local database, offline storage, cart persistence, user data caching, loyalty points cache
- **Triggers**: "database", "cache", "hive", "local storage", "persistence", "offline", "box"
#### 🌐 **api-integration-expert**
- **MUST BE USED for**: Authentication API, OTP verification, product API, loyalty API, order API, project API
- **Triggers**: "API", "HTTP", "dio", "REST", "backend", "authentication", "OTP", "sync"
#### 🏗️ **architecture-expert**
- **MUST BE USED for**: Feature organization, clean architecture setup, dependency injection, navigation structure
- **Triggers**: "architecture", "structure", "organization", "clean code", "refactor", "navigation"
#### ⚡ **performance-expert**
- **MUST BE USED for**: Image caching, list optimization, memory management, app performance
- **Triggers**: "performance", "optimization", "memory", "image cache", "slow", "lag", "scroll"
### 🎯 DELEGATION STRATEGY
**BEFORE starting ANY task, ASK YOURSELF:**
1. "Which of my specialists could handle this better?"
2. "Should I break this into parts for different specialists?"
3. "Would a specialist complete this faster and better?"
### 💼 WORK BALANCE RECOMMENDATION:
- **Simple Tasks (20%)**: Handle independently - quick fixes, minor updates
- **Complex Tasks (80%)**: Delegate to specialists for expert-level results
### 🔧 HOW TO DELEGATE
```
# Explicit delegation examples:
> Use the flutter-widget-expert to create the Diamond/Platinum/Gold loyalty card widget
> Have the riverpod-expert design the authentication and user session state management
> Ask the hive-expert to create the local database schema for products and orders
> Use the api-integration-expert to implement OTP authentication flow
> Have the architecture-expert organize the loyalty program feature structure
> Ask the performance-expert to optimize the product grid scrolling
```
---
## Flutter Best Practices
- Use Flutter 3.x features and Material 3 design
- Implement clean architecture with Riverpod for state management
- Use Hive for local database and offline functionality
- Follow proper dependency injection with Riverpod DI
- Implement proper error handling and user feedback
- Follow iOS and Android platform-specific design guidelines
- Support Vietnamese language (primary) and English (secondary)
- Mobile-first design optimized for phone screens
- Use FontAwesomeIcon
### Hive Best Practices
**IMPORTANT: Box Type Management**
When working with Hive boxes, always use `Box<dynamic>` in data sources and apply `.whereType<T>()` for type-safe queries.
**Reason**: Hive boxes are opened as `Box<dynamic>` in the central HiveService. Re-opening with a specific type causes `HiveError: The box is already open and of type Box<dynamic>`.
**See CODE_EXAMPLES.md → Best Practices → Hive Box Type Management** for correct and incorrect patterns.
### AppBar Standardization
**ALL AppBars must follow this standard pattern** (reference: `products_page.dart`).
**Key Requirements**:
- Black back arrow with explicit color
- Black text title with TextStyle
- Left-aligned title (`centerTitle: false`)
- White background (`AppColors.white`)
- Use `AppBarSpecs.elevation` (not hardcoded values)
- Always add `SizedBox(width: AppSpacing.sm)` after actions
**See CODE_EXAMPLES.md → Best Practices → AppBar Standardization** for standard AppBar and SliverAppBar patterns.
---
## Worker App Project Structure
**See [PROJECT_STRUCTURE.md](PROJECT_STRUCTURE.md)** for the complete project structure with all features, folders, and files.
### Vietnamese Currency Formatting
**IMPORTANT: Always use `toVNCurrency()` extension for displaying Vietnamese currency.**
```dart
// Import the extension
import 'package:worker/core/utils/extensions.dart';
// Usage examples:
final price = 1500000;
Text(price.toVNCurrency()); // Output: "1.500.000 đ"
final total = 25000000.5;
Text(total.toVNCurrency()); // Output: "25.000.001 đ" (rounded)
// In widgets:
Text(
product.price.toVNCurrency(),
style: AppTextStyle.bodyLarge.copyWith(
fontWeight: FontWeight.bold,
color: AppColors.primary,
),
)
// For order totals, cart summaries, payment amounts:
Text('Tổng tiền: ${order.totalAmount.toVNCurrency()}')
```
**DO NOT use:**
- `NumberFormat` directly for VND
- Manual string formatting like `'${price.toString()} đ'`
- Other currency formatters
**The `toVNCurrency()` extension:**
- Formats with dot (.) as thousand separator
- Appends " đ" suffix
- Rounds to nearest integer
- Handles both `int` and `double` values
---
# App Context - Worker Mobile App
## About This App
A comprehensive Flutter mobile application designed for workers in the tile and construction industry. The app enables contractors, architects, distributors, and brokers to manage their loyalty rewards, browse products, create orders, manage construction projects, and track business performance—all through an intuitive mobile interface optimized for speed and efficiency.
## Design References
The `html/` folder contains 25+ HTML mockup files that serve as UI/UX design references:
- Visual design and layout specifications
- Color schemes and branding
- User flow and navigation patterns
- Component designs and interactions
- Form layouts and validation patterns
**These HTML files should be referenced when building Flutter widgets to match the desired design.**
---
## Core Features
### 🔐 Authentication System
#### Login Flow
**Pages**: `login_page.dart`, `otp_verification_page.dart`, `register_page.dart`
**Features**:
- Phone number-based authentication (Vietnamese format)
- 6-digit OTP verification with auto-focus
- Auto-advance between OTP input fields
- Resend OTP with 60-second cooldown timer
- Full registration form with user type selection
- Form validation for all fields
**State Management**: See **CODE_EXAMPLES.md → State Management → Authentication Providers**
**Key Widgets**:
- `PhoneInputField`: Vietnamese phone number format (+84)
- `OTPInputField`: 6-digit auto-focus input
- `UserTypeSelector`: Radio buttons for Contractor/Architect/Distributor/Broker
**Design Reference**: `html/login.html`, `html/otp.html`, `html/register.html`
---
### 🏠 Home Screen with Membership Cards
**Purpose**: Dashboard showing member tier card and quick access to features
**Pages**: `home_page.dart`
**Key Features**:
- **Membership Card Display**:
- Three tier widgets: `DiamondMemberCard`, `PlatinumMemberCard`, `GoldMemberCard`
- Gradient backgrounds (blue-purple for Diamond, grey-silver for Platinum, yellow-gold for Gold)
- Member name, ID, and points balance
- QR code generation for member identification
- Animated card transitions
- **Quick Action Grid**:
- 4-6 icon buttons for main features
- Products, Loyalty, Orders, Projects, Promotions
- **Cart badge**: Dynamic count from `cartItemCountProvider`
- Shows cart item count when > 0
- Hidden when cart is empty
- Updates in real-time across all pages
- **Bottom Navigation**:
- 5 tabs: Home, Products, Loyalty, Account, More
- Active state indicators
- Badge for notifications
- **Floating Action Button**:
- Chat support access
- Positioned bottom-right
- Accent cyan color (#35C6F4)
**State Management**: See **CODE_EXAMPLES.md → State Management → Home Providers**
**Design Reference**: `html/index.html`
---
### 🎁 Loyalty Program System
#### Main Loyalty Page
**Page**: `loyalty_page.dart`
**Features**:
- **Tier Progress Display**:
- Current points and tier
- Progress bar to next tier (%)
- Points needed for next tier
- Animated progress indicator
- **Tier Benefits Cards**:
- Points multiplier info
- Special offers access
- Exclusive discounts
- Priority support
- **Quick Actions**:
- Navigate to rewards, history, referral, gifts
**Widgets**:
- `TierProgressBar`: Custom painted progress with gradient
- `PointsBadge`: Circular points display
- `TierBenefitsCard`: Expandable card with benefits list
**State Management**: See **CODE_EXAMPLES.md → State Management → Loyalty Providers**
**Design Reference**: `html/loyalty.html`
---
#### Rewards Page ✅ IMPLEMENTED
**Page**: `rewards_page.dart`
**Features**:
- **Points Balance Card**: Gradient blue card showing available points and expiring points
- **Category Filter Pills**: Horizontal scrollable chips (Tất cả/Voucher/Sản phẩm/Dịch vụ/Ưu đãi đặc biệt)
- **Gift Grid**: 2-column grid with 6 mock gifts
- **Reward Cards** (improved UI):
- 120px image with CachedNetworkImage
- Title and description (truncated)
- Points cost and button **at bottom** (using Spacer())
- Button states: "Đổi quà" (enabled) or "Không đủ điểm" (disabled)
- **Redemption Flow**:
- Confirmation dialog with gift details and balance after redemption
- Success SnackBar with checkmark icon
- Points deduction via `loyaltyPointsProvider`
**Widgets** (Location: `lib/features/loyalty/presentation/`):
- `widgets/points_balance_card.dart`: Gradient card with points display
- `widgets/reward_card.dart`: Individual gift card with bottom-aligned action
- `pages/rewards_page.dart`: Main rewards screen
**State Management**: See **CODE_EXAMPLES.md → State Management → Loyalty Providers → Rewards Page Providers**
**Navigation**:
- Route: `/loyalty/rewards` (RouteNames in app_router.dart)
- Accessible from home quick action "Đổi quà"
**Design Reference**: `html/loyalty-rewards.html`
---
#### Points History Page
**Page**: `points_history_page.dart`
**Features**:
- List of all points transactions
- Transaction cards showing:
- Type (earned/spent) with icon and color
- Points amount (+/- display)
- Description
- Date and time
- New balance after transaction
- Filter by date range (Today/Week/Month/All)
- Dispute button for each transaction
- Pull-to-refresh
**Widgets**:
- `PointsTransactionCard`: Card with transaction details
- `DateRangeFilter`: Chip filter row
- `DisputeButton`: Opens support dialog
**Design Reference**: `html/points-history.html`
---
#### Referral Program Page
**Page**: `referral_page.dart`
**Features**:
- User avatar and tier display
- Total referrals count
- Total points earned from referrals
- Referral code (large, copy-able)
- Referral link (copy and share buttons)
- Share sheet integration (WhatsApp, Telegram, etc.)
- Benefits explanation cards
- How it works guide
**Widgets**:
- `ReferralInfoCard`: Stats display
- `ReferralCodeDisplay`: Large code with copy button
- `ReferralLinkShare`: Link with copy/share buttons
- `ReferralShareSheet`: Bottom sheet with share options
**State Management**: See **CODE_EXAMPLES.md → State Management → Referral Provider**
**Design Reference**: `html/referral.html`
---
#### My Gifts Page
**Page**: `my_gifts_page.dart`
**Features**:
- Tabs: Active (valid), Used, Expired
- Gift cards showing:
- Gift image and title
- Gift code (copy-able)
- Valid from/to dates
- Usage instructions
- Status badge
- Use button (for active gifts)
- Empty state for each tab
- Filter and sort options
**Widgets**:
- `GiftCard`: Card with gift details and actions
- `GiftStatusBadge`: Color-coded status (green/grey/red)
- `GiftCodeCopy`: Code with copy button
**Design Reference**: `html/my-gifts.html`
---
### 🛍️ Products & Shopping
#### Products Page
**Page**: `products_page.dart`
**Features**:
- Search bar with real-time filtering
- Category filter chips (horizontal scroll)
- Product grid (2 columns)
- Product cards showing:
- Image with cached_network_image
- Product name and SKU
- Price (with sale price if applicable)
- Stock indicator
- Add to cart button
- Pull-to-refresh
- Infinite scroll pagination
- Empty state
**Widgets**:
- `ProductGrid`: GridView.builder with pagination
- `ProductCard`: Card with image, info, and actions
- `ProductSearchBar`: Search with clear button
- `CategoryFilterChips`: Horizontal chip list
**State Management**: See **CODE_EXAMPLES.md → State Management → Products Providers**
**Design Reference**: `html/products.html`
---
#### Cart & Checkout
**Pages**: `cart_page.dart`, `checkout_page.dart`, `order_success_page.dart`
**Cart Features**:
- List of cart items
- Item cards with:
- Product image and name
- Price per unit
- Quantity selector (+/-)
- Remove button
- Line total
- Cart summary:
- Subtotal
- Discount (if applied)
- Shipping
- Total
- Clear cart button
- Checkout button
**Checkout Features**:
- Delivery address selection/entry
- Payment method selection (COD/Bank Transfer/Card/E-wallet)
- Order summary
- Place order button with loading state
- Form validation
**Success Features**:
- Success animation (Lottie)
- Order number display
- Estimated delivery date
- Order details summary
- Action buttons: View order, Continue shopping
**State Management**: See **CODE_EXAMPLES.md → State Management → Cart Providers**
**Design Reference**: `html/cart.html`, `html/checkout.html`, `html/order-success.html`
---
### 📦 Orders Management
**Pages**: `orders_page.dart`, `order_detail_page.dart`, `payments_page.dart`
**Orders Features**:
- Tab bar for status filtering:
- All, Pending, Processing, Shipping, Completed, Cancelled
- Order cards showing:
- Order number and date
- Customer info (for distributors/brokers)
- Product list (collapsed)
- Total amount
- Status badge (color-coded)
- Action buttons (View details, Track)
- Search by order number
- Filter by date range
- Pull-to-refresh
**Order Detail Features**:
- Full order information
- Timeline showing order status progression
- Product list with images
- Delivery address
- Payment info
- Action buttons (Contact support, Reorder)
**Payments Features**:
- List of payment transactions
- Payment cards showing:
- Payment ID
- Order reference
- Amount
- Payment method
- Date
- Status (Processing/Completed)
- Search and filter options
**State Management**: See **CODE_EXAMPLES.md → State Management → Orders Providers**
**Design Reference**: `html/orders.html`, `html/payments.html`
---
### 🏗️ Projects & Quotes Management
#### Projects
**Pages**: `projects_page.dart`, `project_create_page.dart`, `project_detail_page.dart`
**Projects Features**:
- List of construction projects
- Project cards showing:
- Project name and code
- Client/owner info
- Location
- Start and end dates
- Progress bar (%)
- Status badge (Planning/In Progress/Completed)
- Budget/value
- Create new project FAB
- Filter by status, date, client
- Search projects
**Project Create Features**:
- Form with fields:
- Project name and code
- Client name and phone
- Location/address
- Start/end dates
- Project type (Residential/Commercial/Industrial)
- Budget
- Description and notes
- Form validation
- Save draft functionality
- Date pickers
- Auto-generate project code option
**State Management**: See **CODE_EXAMPLES.md → State Management → Projects Providers**
**Design Reference**: `html/projects.html`, `html/project-create.html`
---
#### Quotes
**Pages**: `quotes_page.dart`, `quote_create_page.dart`
**Quotes Features**:
- List of quotations
- Quote cards showing:
- Quote number and date
- Client info
- Total amount
- Validity period
- Status badge (Draft/Sent/Accepted/Rejected/Expired)
- Actions:
- Create new quote
- Edit draft
- Send to client
- Convert to order
- Duplicate
- Search and filter
**Design Reference**: `html/quotes.html`
---
### 💬 Chat Support
**Pages**: `chat_page.dart`
**Features**:
- Real-time chat interface
- Message bubbles (sent/received)
- Timestamp for messages
- User avatars
- Typing indicator animation
- Message input with send button
- File attachment button
- Auto-scroll to latest message
- Read receipts
- Support agent info header
**Widgets**:
- `MessageBubble`: Custom bubble with tail
- `MessageInput`: Text field with send button
- `TypingIndicator`: Animated dots
- `ChatAppBar`: Custom app bar with agent info
**State Management**: See **CODE_EXAMPLES.md → State Management → Chat Providers**
**Design Reference**: `html/chat.html`
---
### 👤 Account Management
#### Account Page
**Page**: `account_page.dart`
**Features**:
- Profile header with avatar, name, tier, points
- Menu sections:
- Personal: Profile, Password, Addresses
- Business: Company info, Tax info
- Settings: Notifications, Language, Theme
- Support: Help, Contact, Terms, Privacy
- App: Version, Logout
- Navigation to sub-pages
- Logout confirmation dialog
**Design Reference**: `html/account.html`
---
#### Profile Edit
**Page**: `profile_edit_page.dart`
**Features**:
- Avatar upload with image picker
- Image cropping
- Form fields:
- Full name
- Email
- Phone (read-only)
- Date of birth
- Gender
- Company name
- Tax ID
- Business address
- User type
- Form validation
- Unsaved changes warning
- Save/cancel buttons
**Widgets**:
- `AvatarPicker`: Image picker with crop
- `DatePickerField`: Date selection
- `GenderSelector`: Radio buttons
**Design Reference**: `html/profile-edit.html`
---
#### Addresses Management
**Pages**: `addresses_page.dart`, `address_form_page.dart`
**Features**:
- List of saved addresses
- Address cards with:
- Label (Home/Office/Other)
- Recipient name and phone
- Full address
- Default badge
- Edit/delete actions
- Add new address FAB
- Set as default toggle
- Form with:
- Recipient name
- Phone number
- Address fields (Street, City, District, Ward, Postal code)
- Address type
- Set as default checkbox
- Form validation
**Design Reference**: `html/addresses.html`
---
#### Change Password
**Page**: `password_change_page.dart`
**Features**:
- Form with:
- Current password
- New password
- Confirm new password
- Show/hide password toggles
- Password strength indicator
- Requirements checklist:
- Min 8 characters
- Uppercase letter
- Lowercase letter
- Number
- Special character
- Real-time validation
- Success message and redirect
**Widgets**:
- `PasswordStrengthIndicator`: Visual strength meter
- `PasswordRequirements`: Checklist with check/cross icons
**Design Reference**: `html/password-change.html`
---
### 🎉 Promotions & Notifications
#### Promotions
**Page**: `promotions_page.dart`
**Features**:
- List of active promotions
- Promotion cards with:
- Banner image
- Title and description
- Discount percentage/amount
- Validity period
- Terms and conditions
- Apply/claim button
- Filter by category
- Status indicators (Active/Upcoming/Expired)
**Design Reference**: `html/promotions.html`
---
#### Notifications
**Page**: `notifications_page.dart`
**Features**:
- Tabs: All, Orders, System, Promotions
- Notification cards with:
- Icon/avatar
- Title and content
- Timestamp
- Read/unread indicator
- Action buttons
- Mark as read
- Clear all button
- Pull-to-refresh
- Badge count on bottom nav
**Design Reference**: `html/notifications.html`
---
## UI/UX Design System
### Color Palette
See **CODE_EXAMPLES.md → UI/UX Components → Color Palette** for the complete color system including:
- Primary colors (blue shades)
- Status colors (success, warning, danger, info)
- Neutral grays
- Tier gradients (Diamond, Platinum, Gold)
### Typography
See **CODE_EXAMPLES.md → UI/UX Components → Typography** for text styles:
- Display, headline, title, body, and label styles
- Roboto font family
- Font sizes and weights
### Component Specifications
All component specifications are documented in **CODE_EXAMPLES.md → UI/UX Components**:
- **Member Card Design**: Dimensions, padding, QR code specs, points display
- **Status Badges**: Color mapping for order statuses
- **Bottom Navigation**: Heights, icon sizes, colors
- **Floating Action Button**: Size, elevation, colors, position
- **AppBar Specifications**: Standard pattern with helper method
**AppBar Usage Notes**:
- ALL pages use the standard AppBar pattern
- Back arrow is always black with explicit color
- Title is always left-aligned (`centerTitle: false`)
- Title text is always black
- Background is always white
- Actions always end with `SizedBox(width: AppSpacing.sm)` spacing
- For SliverAppBar, add `pinned: true` property
---
## Technical Architecture
### State Management (Riverpod 2.x)
All state management patterns and implementations are documented in **CODE_EXAMPLES.md → State Management**, including:
- Authentication State with phone login and OTP verification
- All feature-specific providers (Home, Loyalty, Products, Cart, Orders, Projects, Chat)
- Provider patterns and best practices
### Domain Entities & Data Models
The app follows clean architecture with domain entities and Hive data models based on the database schema in `database.md`.
#### **Domain Entities (28 files)**
Pure business logic entities with no external dependencies. All entities use freezed for immutability.
**Auth Feature** (`lib/features/auth/domain/entities/`)
- `user.dart` - User with role, status, loyalty tier, company info
- `user_session.dart` - User session with device tracking
**Products Feature** (`lib/features/products/domain/entities/`)
- `product.dart` - Product with images, specs, 360 view, ERPNext integration
- `stock_level.dart` - Inventory tracking (available/reserved/ordered)
- `category.dart` - Product categories
**Cart Feature** (`lib/features/cart/domain/entities/`)
- `cart.dart` - Shopping cart with sync status
- `cart_item.dart` - Cart line items
**Orders Feature** (`lib/features/orders/domain/entities/`)
- `order.dart` - Orders with status, addresses, ERPNext integration
- `order_item.dart` - Order line items with discounts
- `invoice.dart` - Invoices with type, status, payment tracking
- `payment_line.dart` - Payment transactions with method and status
**Loyalty Feature** (`lib/features/loyalty/domain/entities/`)
- `loyalty_point_entry.dart` - Points transactions with type, source, complaints
- `gift_catalog.dart` - Redeemable gifts with category, points cost
- `redeemed_gift.dart` - User's redeemed gifts with voucher codes
- `points_record.dart` - Invoice submissions for manual points
**Projects Feature** (`lib/features/projects/domain/entities/`)
- `project_submission.dart` - Completed project submissions with photos
- `design_request.dart` - Design consultation requests
**Quotes Feature** (`lib/features/quotes/domain/entities/`)
- `quote.dart` - Quotations with status, validity, conversion tracking
- `quote_item.dart` - Quote line items with price negotiation
**Chat Feature** (`lib/features/chat/domain/entities/`)
- `chat_room.dart` - Chat rooms with type, participants
- `message.dart` - Messages with content type, attachments, read status
**Notifications Feature** (`lib/features/notifications/domain/entities/`)
- `notification.dart` - User notifications with type-based data
**Showrooms Feature** (`lib/features/showrooms/domain/entities/`)
- `showroom.dart` - Virtual showrooms with 360 views, gallery
- `showroom_product.dart` - Products used in showrooms
**Account Feature** (`lib/features/account/domain/entities/`)
- `payment_reminder.dart` - Payment reminders with scheduling
- `audit_log.dart` - System audit trail
**Home Feature** (`lib/features/home/domain/entities/`)
- `member_card.dart` - Membership card display
- `promotion.dart` - Promotional campaigns
#### **Hive Data Models (25 files)**
Hive CE models for offline-first local storage. All models extend `HiveObject` with proper type adapters.
**Type ID Allocation:**
- Models: 0-24 (user_model=0, user_session_model=1, product_model=2, etc.)
- Enums: 30-50 (UserRole=30, UserStatus=31, LoyaltyTier=32, etc.)
**Model Features:**
- `@HiveType` with unique typeId
- `@HiveField` for all properties
- `fromJson()` / `toJson()` for API serialization
- `toEntity()` / `fromEntity()` for domain conversion
- Helper methods for JSONB fields
- Full documentation
**All models are located in:** `lib/features/*/data/models/`
- Auth: `user_model.dart`, `user_session_model.dart`
- Products: `product_model.dart`, `stock_level_model.dart`
- Cart: `cart_model.dart`, `cart_item_model.dart`
- Orders: `order_model.dart`, `order_item_model.dart`, `invoice_model.dart`, `payment_line_model.dart`
- Loyalty: `loyalty_point_entry_model.dart`, `gift_catalog_model.dart`, `redeemed_gift_model.dart`, `points_record_model.dart`
- Projects: `project_submission_model.dart`, `design_request_model.dart`
- Quotes: `quote_model.dart`, `quote_item_model.dart`
- Chat: `chat_room_model.dart`, `message_model.dart`
- Notifications: `notification_model.dart`
- Showrooms: `showroom_model.dart`, `showroom_product_model.dart`
- Account: `payment_reminder_model.dart`, `audit_log_model.dart`
#### **Enums (21 types)**
All enums are defined in `lib/core/database/models/enums.dart` with Hive type adapters:
**User & Auth:**
- `UserRole` - admin, customer, contractor, architect, distributor, broker
- `UserStatus` - active, inactive, pending, suspended, banned
- `LoyaltyTier` - diamond, platinum, gold
**Orders & Payments:**
- `OrderStatus` - draft, pending, confirmed, processing, shipped, delivered, completed, cancelled, returned, refunded
- `InvoiceType` - sales, proforma, credit_note, debit_note
- `InvoiceStatus` - draft, sent, viewed, overdue, paid, partially_paid, cancelled
- `PaymentMethod` - cash, bank_transfer, credit_card, debit_card, e_wallet, cod
- `PaymentStatus` - pending, processing, completed, failed, refunded
**Loyalty & Gifts:**
- `EntryType` - earn, spend, adjust, expire, reversal
- `EntrySource` - purchase, referral, promotion, bonus, manual, project_submission, design_request, points_record
- `ComplaintStatus` - pending, reviewing, approved, rejected, resolved
- `GiftCategory` - voucher, product, service, experience, discount
- `GiftStatus` - active, used, expired, cancelled
- `PointsStatus` - pending, approved, rejected
**Projects & Quotes:**
- `ProjectType` - residential, commercial, industrial, hospitality, retail, office, other
- `SubmissionStatus` - pending, reviewing, approved, rejected
- `DesignStatus` - submitted, assigned, in_progress, completed, delivered, revision_requested, approved, cancelled
- `QuoteStatus` - draft, sent, viewed, negotiating, accepted, rejected, expired, converted
**Chat:**
- `RoomType` - support, sales, quote, order
- `ContentType` - text, image, file, product, location
- `ReminderType` - payment_due, overdue, final_notice, custom
**Detailed Documentation:**
- See `DOMAIN_ENTITIES_SUMMARY.md` for entity details
- See `HIVE_MODELS_REFERENCE.md` for model templates and usage
- See `lib/core/constants/storage_constants.dart` for Type ID reference
---
## Performance Optimization
All performance optimization patterns are documented in **CODE_EXAMPLES.md → Performance Optimization**:
- **Image Caching**: Using CachedNetworkImage with proper configuration
- **List Performance**: RepaintBoundary, AutomaticKeepAliveClientMixin, cacheExtent
- **State Optimization**: Using .select(), family modifiers, provider best practices
---
## Offline Strategy
All offline strategy patterns are documented in **CODE_EXAMPLES.md → Offline Strategy**:
- **Data Sync Flow**: Complete sync implementation with connectivity monitoring
- **Offline Queue**: Request queuing system for failed API calls
## Localization (Vietnamese Primary)
All localization setup and usage examples are documented in **CODE_EXAMPLES.md → Localization**:
- **Setup**: l10n.yaml configuration, Vietnamese and English .arb files
- **Usage**: LoginPage example showing how to use AppLocalizations in widgets
---
## Deployment
All deployment configurations are documented in **CODE_EXAMPLES.md → Deployment**:
- **Android**: build.gradle configuration with signing and build settings
- **iOS**: Podfile configuration with deployment target settings
---
## Development Workflow
### Feature Development Process
1. **Review HTML Reference**: Check `html/` folder for design spec
2. **Design Data Layer**: Models, repositories, data sources
3. **Implement Domain Layer**: Entities, use cases
4. **Create Providers**: Riverpod state management
5. **Build UI**: Match HTML (in 375px width) reference design
6. **Test**: Unit, widget, integration tests
7. **Optimize**: Performance profiling
### Code Review Checklist
- [ ] Matches HTML reference design
- [ ] Follows clean architecture
- [ ] Proper error handling
- [ ] Online-first approach
- [ ] Performance optimized
- [ ] Proper state management with Riverpod
- [ ] Hive models properly defined
- [ ] Vietnamese localization
- [ ] Tests written and passing
- [ ] Code documented
---
## Roadmap
### Phase 1 - Core Features ✅
- ✅ Authentication (login, OTP, register)
- ✅ Home with member cards (3 tiers)
- ✅ Product browsing with search and filters
- ✅ Shopping cart with dynamic badge
- ✅ Favorites system with Hive persistence
- ✅ Order management
- ✅ Project and quote management
- ✅ Account management
- ✅ Promotions with detail pages
### Phase 1.5 - Loyalty System ✅ RECENT
-**Rewards/Gift Redemption Page** (Dec 2024)
- Points balance card with gradient
- Category filtering (Voucher/Product/Service/Discount)
- 2-column gift grid with 6 mock items
- Redemption flow with confirmation dialog
- Points deduction and success feedback
-**UI Standardization** (Dec 2024)
- All AppBars now follow consistent pattern
- Dynamic cart badge across all pages
- Hive Box<dynamic> best practices documented
- 🔄 Points history page (planned)
- 🔄 Referral program page (planned)
- 🔄 My gifts page (planned)
- 🔄 Chat support (planned)
### Phase 2 - Backend Integration 🔄
- REST API integration
- Real-time WebSocket for chat
- Push notifications (FCM)
- Payment gateway
- Cloud image storage
- Analytics tracking
### Phase 3 - Advanced Features 📋
- QR code scanner (loyalty & products)
- Barcode scanning
- Geolocation for nearby stores
- Photo gallery for projects
- PDF report generation
- Biometric authentication
- Offline mode with background sync
- AR product visualization
---
## Remember: ALWAYS DELEGATE TO SPECIALISTS FOR BETTER RESULTS!
When working on this Flutter Worker app:
- **UI Tasks** → flutter-widget-expert
- **State Management** → riverpod-expert
- **Database/Caching** → hive-expert
- **API Integration** → api-integration-expert
- **Architecture Decisions** → architecture-expert
- **Performance Issues** → performance-expert
**Think delegation first, implementation second!**
---
## Recent Updates & Implementation Notes (December 2024)
### ✅ Rewards/Gift Redemption System
**Status**: Fully implemented with mock data
**Implementation Details**:
1. **Providers** (`lib/features/loyalty/presentation/providers/`):
- `loyalty_points_provider.dart` - Manages user points (9,750 available, 1,200 expiring)
- `gifts_provider.dart` - 6 mock gifts matching HTML design
- `selectedGiftCategoryProvider` - Category filter state
- `filteredGiftsProvider` - Category-based filtering
- `hasEnoughPointsProvider.family` - Points validation per gift
2. **Widgets** (`lib/features/loyalty/presentation/widgets/`):
- `points_balance_card.dart` - Gradient blue card with points display
- `reward_card.dart` - Gift card with bottom-aligned action button
3. **Pages** (`lib/features/loyalty/presentation/pages/`):
- `rewards_page.dart` - Main screen with RefreshIndicator
4. **Route**: `/loyalty/rewards` in `app_router.dart`
**Key Features**:
- 2-column grid layout with `childAspectRatio: 0.7`
- Category filtering: Tất cả/Voucher/Sản phẩm/Dịch vụ/Ưu đãi đặc biệt
- Bottom-aligned buttons using `Expanded` + `Spacer()`
- Redemption dialog with points calculation
- Success feedback with SnackBar
### ✅ AppBar Standardization
**Status**: Completed across all pages
See **CODE_EXAMPLES.md → Best Practices → AppBar Standardization** for the standard pattern.
**Updated Pages**:
- `cart_page.dart` - Lines 84-103
- `favorites_page.dart` - Lines 79-115
- `rewards_page.dart` - Lines 35-48
- `promotion_detail_page.dart` - Lines 59-86 (loading/error), 130-161 (SliverAppBar)
- `product_detail_page.dart` - Already correct ✅
### ✅ Dynamic Cart Badge
**Status**: Implemented across home and products pages
See **CODE_EXAMPLES.md → State Management → Cart Providers → Dynamic Cart Badge** for the implementation.
**Behavior**:
- Shows total quantity across all cart items
- Hidden when cart is empty
- Updates in real-time via Riverpod
- Navigation via `RouteNames.cart` constant
### ✅ Hive Box Type Management
**Status**: Best practices documented and implemented
**Problem Solved**: `HiveError: The box "favorite_box" is already open and of type Box<dynamic>`
**Solution Applied**:
- All data sources now use `Box<dynamic>` getters
- Type-safe queries via `.whereType<T>()`
- Applied to `favorites_local_datasource.dart`
See **CODE_EXAMPLES.md → Best Practices → Hive Box Type Management** for the correct pattern.
### 🔄 Next Steps (Planned)
1. Points history page with transaction list
2. Referral program page with share functionality
3. My gifts page with tabs (Active/Used/Expired)
4. Backend API integration for loyalty endpoints
5. Real redemption flow with gift codes
### 📝 Code Quality Checklist
All recent implementations follow:
- ✅ Clean architecture (data/domain/presentation)
- ✅ Riverpod state management
- ✅ Hive for local persistence
- ✅ Material 3 design system
- ✅ Vietnamese localization
- ✅ AppBar standardization
- ✅ CachedNetworkImage for all remote images
- ✅ Proper error handling
- ✅ Loading states (CircularProgressIndicator)
- ✅ Empty states with helpful messages