A comprehensive Flutter-based order management application with intelligent features including fuzzy search, AI-powered auto-status assignment, ERP import capabilities, and automated email notifications.
- Flutter SDK: Version 3.16.0 or higher
- Git: For cloning the repository
- IDE: VS Code, Android Studio, or your preferred editor
git clone https://github.com/yourusername/orderengine.git
cd orderengine
flutter pub getflutter runThat's it! The application is pre-configured with:
- β Supabase database connection
- β Email notification service
- β Sample data ready to use
- Supabase: Database and backend services
- Resend: Email notification service
- Sample Data: Pre-loaded for testing
# Run in debug mode
flutter run
# Run with specific device
flutter run -d chrome # Web
flutter run -d android # Android
flutter run -d ios # iOS
# Run tests
flutter test
# Build for production
flutter build web
flutter build apk --releaselib/
βββ main.dart # App entry point
βββ models/ # Data models
βββ screens/ # UI screens
βββ services/ # API and business logic
βββ utils/ # Utilities and helpers
βββ widgets/ # Reusable components
- Fuzzy Search: Intelligent item matching
- Auto Status Assignment: AI-based order status
- ERP Import: File import with fuzzy matching
- Email Notifications: Automated customer emails
- Database Management: CRUD operations with Supabase
- Flutter issues:
flutter doctor - Build issues:
flutter clean && flutter pub get - Database issues: Check Supabase project status
- Email issues: Verify Resend API configuration
The app uses build-time environment variables for production. For development, check lib/utils/supabase_config.dart for configuration details.
# Run all tests
flutter test
# Run specific test
flutter test test/fuzzy_matcher_test.dart- Web: Deployed to Firebase Hosting
- Mobile: Build APK/IPA for distribution
The app currently uses .env file for development. This is already configured.
# Web build with environment variables
flutter build web --dart-define=SUPABASE_URL=https://your-project.supabase.co --dart-define=SUPABASE_ANON_KEY=your-anon-key
# Android build with environment variables
flutter build apk --release --dart-define=SUPABASE_URL=https://your-project.supabase.co --dart-define=SUPABASE_ANON_KEY=your-anon-key
# iOS build with environment variables
flutter build ios --release --dart-define=SUPABASE_URL=https://your-project.supabase.co --dart-define=SUPABASE_ANON_KEY=your-anon-keyCreate a build script to avoid typing long commands:
#!/bin/bash
# build.sh
flutter build web \
--dart-define=SUPABASE_URL=https://zlsevcwieqzyccxholsz.supabase.co \
--dart-define=SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inpsc2V2Y3dpZXF6eWNjeGhvbHN6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTExMzg0NzEsImV4cCI6MjA2NjcxNDQ3MX0.X5LGSLOtxKWEG4svJ-OnJLa14NWLuEi6j1UPk4wt4CI \
--dart-define=RESEND_API_KEY=your-resend-api-key# .github/workflows/build.yml
- name: Build Flutter Web
run: |
flutter build web \
--dart-define=SUPABASE_URL=${{ secrets.SUPABASE_URL }} \
--dart-define=SUPABASE_ANON_KEY=${{ secrets.SUPABASE_ANON_KEY }} \
--dart-define=RESEND_API_KEY=${{ secrets.RESEND_API_KEY }}- Build-time variables (--dart-define) - Highest priority
- Environment variables (from .env file) - Fallback
- Default values - Lowest priority
The app is configured to use .env file for development and build-time variables for production. Check lib/utils/supabase_config.dart for the implementation details.
- Web:
flutter run -d chrome - Android:
flutter run -d android - iOS:
flutter run -d ios(macOS only)
- Flutter issues: Run
flutter doctorand fix any issues - Build issues: Run
flutter clean && flutter pub get - Connection issues: Contact support if database/email services are down
- Database: Pre-configured Supabase project with all tables and sample data
- Email Service: Resend integration for order notifications
- Sample Data: Ready-to-use customers, items, and orders
- All Features: Fuzzy search, auto status assignment, ERP import, and more
Order Engine is a cross-platform order management application built with Flutter. It enables businesses to manage customers, items, and orders, import data from ERP systems, and automate order status assignment. The app is deployed on Firebase Hosting and uses Supabase for backend data and email services.
- Order Management: Create, edit, view, and search orders with real-time updates
- Customer Management: Add, edit, and manage customer information
- Item Management: Add, edit, and manage inventory items with categories
- Database Management: Admin interface for managing customers and items
- ERP Import: Import orders from ERP A (pipe-delimited) and ERP B (CSV) flat files
- Fuzzy Matching: Intelligent item code matching with typo tolerance
- Auto Status Assignment: AI-based logic to automatically assign order status based on order details
- Email Notifications: Sends order confirmation and update emails to customers
- Responsive Design: Works seamlessly on web, desktop, and mobile devices
- Fuzzy Search: Search orders and items with typo-tolerance
- Real-time Filtering: Instant search results as you type
- Order Details: Comprehensive order view with customer and item information
- Create Customer: Add new customers with name, email, phone, and address
- Edit Customer: Update existing customer information
- View Customer Details: See complete customer profile and order history
- Delete Customer: Remove customers (with order history preservation)
- Search Customers: Find customers by name or email
- Customer List: View all customers with pagination and sorting
- Customer ID: Unique identifier (auto-generated or custom)
- Name: Full customer name
- Email: Customer email address (optional, for notifications)
- Phone: Contact phone number
- Address: Physical address (optional)
- Created Date: When customer was added
- Order Count: Number of orders placed by customer
- Order History: View all orders placed by a specific customer
- Email Notifications: Receive order confirmations and updates
- Data Validation: Ensures required fields are completed
- Duplicate Prevention: Checks for existing customers before creation
- Create Item: Add new inventory items with detailed information
- Edit Item: Update item details, pricing, and availability
- View Item Details: See complete item information and usage statistics
- Delete Item: Remove items (with order history preservation)
- Search Items: Find items by name, code, or category
- Item List: View all items with filtering and sorting options
- Item Code: Unique product identifier
- Name: Product name
- Description: Detailed product description
- Unit Price: Price per unit
- Category: Product category (Electronics, Office Supplies, etc.)
- Availability: Whether item is in stock
- Image URL: Product image link (optional)
- Attributes: Additional product specifications (JSON format)
- Fuzzy Matching: Intelligent item code matching for ERP imports
- Category Management: Organize items by categories
- Price Tracking: Monitor price changes over time
- Stock Management: Track item availability
- Image Support: Optional product images
- Flexible Attributes: Custom fields for specific item types
- Create Order: Build new orders with multiple items
- Edit Order: Modify existing orders (items, quantities, status)
- View Order Details: Comprehensive order information
- Delete Order: Remove orders (with proper cleanup)
- Search Orders: Find orders by ID, customer, or items
- Order List: View all orders with filtering and sorting
- Order ID: Unique order identifier
- Customer ID: Reference to customer who placed the order
- Order Date: When order was created
- Status: Current order status (Pending, Processing, Completed, Cancelled)
- Total Amount: Sum of all items in the order
- Items: List of ordered items with quantities and prices
- Updated Date: Last modification timestamp
- Multi-Item Orders: Add multiple items to a single order
- Quantity Management: Specify quantities for each item
- Price Calculation: Automatic total calculation
- Status Tracking: Monitor order progress
- Auto Status Assignment: Intelligent status assignment based on order details
- Email Notifications: Automatic customer notifications
The system automatically assigns order status based on:
High-Value Orders (>$1000):
- Assigned "Processing" status for priority handling
- Triggers special notifications
Fragile Items:
- Orders with fragile items get "Processing" status
- Requires special packaging considerations
Regular Customers:
- Customers with order history get faster processing
- Status may be upgraded based on customer loyalty
Complex Orders:
- Multiple items or high quantities may affect status
- System considers order complexity in assignment
- Pending: Default status for new orders
- Processing: Order is being prepared or shipped
- Completed: Order has been successfully delivered
- Cancelled: Order has been cancelled
- Subtotal: Sum of (item price Γ quantity) for each item
- Total Amount: Final order total
- Item Count: Number of unique items in order
- Quantity Total: Total number of units ordered
- One customer can have multiple orders
- Customer information is preserved even if orders are deleted
- Customer email is used for order notifications
- One item can be in multiple orders
- Item information is preserved for order history
- Item availability affects order creation
- One order can contain multiple items
- Each order item has quantity and price information
- Order total is calculated from all items
- Required Fields: Customer name, item code, order items
- Data Types: Proper validation for emails, phone numbers, prices
- Business Rules: Logical constraints (positive quantities, valid prices)
- Foreign Keys: Proper relationships between tables
- Cascade Rules: Appropriate deletion behavior
- Unique Constraints: Prevents duplicate entries
- API Key Protection: Sensitive keys stored in backend only
- Input Sanitization: Prevents injection attacks
- Access Control: Proper database permissions
The fuzzy matching system uses a dynamic programming approach based on Levenshtein distance:
// Algorithm: Dynamic Programming Matrix
// Time Complexity: O(mΓn) where m, n are string lengths
// Space Complexity: O(mΓn)
static int _levenshteinDistance(String s1, String s2) {
final matrix = List.generate(s1.length + 1,
(i) => List.generate(s2.length + 1, (j) => 0));
// Initialize first row and column
for (int i = 0; i <= s1.length; i++) matrix[i][0] = i;
for (int j = 0; j <= s2.length; j++) matrix[0][j] = j;
// Fill matrix using dynamic programming
for (int i = 1; i <= s1.length; i++) {
for (int j = 1; j <= s2.length; j++) {
final cost = s1[i - 1] == s2[j - 1] ? 0 : 1;
matrix[i][j] = [
matrix[i - 1][j] + 1, // deletion
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j - 1] + cost, // substitution
].reduce((a, b) => a < b ? a : b);
}
}
return matrix[s1.length][s2.length];
}// Normalized similarity score (0.0 to 1.0)
similarity = 1.0 - (levenshtein_distance / max_string_length)-
Exact Contains Match (Highest Priority)
- Direct substring matching
- Case-insensitive comparison
- Immediate return if found
-
Character-Level Typo Detection
- Handles common typos like "llaptop" β "laptop"
- Double letter correction algorithm
- Character-by-character comparison with skip logic
-
Enhanced Similarity Matching
- Character-based: Standard Levenshtein distance
- Word-based: Handles word order variations
- Combined: Returns the higher of both scores
// Algorithm: Word-based similarity with sorting
static double calculateWordSimilarity(String s1, String s2) {
// Split into words and normalize
final words1 = s1.toLowerCase().split(RegExp(r'[^a-z0-9]+'))
.where((w) => w.isNotEmpty).toList();
final words2 = s2.toLowerCase().split(RegExp(r'[^a-z0-9]+'))
.where((w) => w.isNotEmpty).toList();
// Sort words to handle order variations
words1.sort();
words2.sort();
// Calculate similarity between sorted word lists
return calculateSimilarity(words1.join(' '), words2.join(' '));
}Example: "blue pen" matches "pen blue" with 100% similarity
The system uses a multi-stage matching approach for item codes:
// Remove special characters and convert to lowercase
normalizedCode = legacyItemCode.toLowerCase()
.replaceAll(RegExp(r'[^a-z0-9]'), '');Examples:
- "LAP-TOP-001" β "laptop001"
- "Blue Pen (Premium)" β "bluepenpremium"
- "iPhone 14 Pro Max" β "iphone14promax"
- Normalized Code Match: Compare normalized versions
- Original Code Match: Case-insensitive original comparison
- Name Match: Compare against item names
// Enhanced similarity calculation
final codeScore = FuzzyMatcher.calculateEnhancedSimilarity(
legacyItemCode, item.itemCode);
final nameScore = FuzzyMatcher.calculateEnhancedSimilarity(
legacyItemCode, item.name);
final normalizedScore = FuzzyMatcher.calculateEnhancedSimilarity(
normalizedCode, itemCodeNormalized);
// Return best score from all comparisons
bestScore = [codeScore, nameScore, normalizedScore]
.reduce((a, b) => a > b ? a : b);- High Threshold (0.8-1.0): Strict matching, fewer false positives
- Medium Threshold (0.6-0.8): Balanced accuracy and flexibility
- Low Threshold (0.4-0.6): Lenient matching, more suggestions
// Generate ranked suggestions for manual review
List<ItemMatch> getItemSuggestions(String legacyItemCode) {
final suggestions = <ItemMatch>[];
for (final item in availableItems) {
final score = calculateBestSimilarity(legacyItemCode, item);
if (score >= minimumThreshold) {
suggestions.add(ItemMatch(item: item, score: score));
}
}
// Sort by score (highest first)
suggestions.sort((a, b) => b.score.compareTo(a.score));
return suggestions;
}The auto status assignment uses a weighted scoring system with multiple contextual factors:
// Multi-factor context analysis
Map<String, dynamic> _analyzeOrderContext(
List<OrderItem> orderItems,
double totalAmount,
List<Item> availableItems,
) {
return {
'urgency_indicators': _detectUrgencyPatterns(itemNames),
'complexity_score': _calculateComplexityScore(itemNames, categories),
'value_analysis': _analyzeValuePatterns(totalAmount, orderItems),
'seasonal_factors': _detectSeasonalPatterns(),
'customer_patterns': _analyzeCustomerPatterns(totalAmount),
'item_diversity': itemCount,
'quantity_pattern': totalQuantity,
'price_distribution': avgPrice,
'category_mix': uniqueCategories,
};
}// Keyword-based urgency scoring
static Map<String, double> _detectUrgencyPatterns(List<String> itemNames) {
final urgencyKeywords = {
'urgent': 0.9, 'rush': 0.8, 'express': 0.7,
'priority': 0.6, 'asap': 0.9, 'emergency': 0.95,
'immediate': 0.8, 'quick': 0.5, 'fast': 0.6,
'instant': 0.7, 'same_day': 0.8, 'overnight': 0.7,
};
final urgencyScores = <String, double>{};
for (final keyword in urgencyKeywords.keys) {
final matches = itemNames.where((name) =>
name.contains(keyword)).length;
if (matches > 0) {
urgencyScores[keyword] = urgencyKeywords[keyword]! * matches;
}
}
return urgencyScores;
}// Multi-factor complexity calculation
static double _calculateComplexityScore(
List<String> itemNames,
List<String> categories,
) {
double complexity = 0.0;
// Item complexity factors
final complexItems = ['electronics', 'fragile', 'custom', 'assembled'];
final simpleItems = ['basic', 'standard', 'simple', 'regular'];
for (final name in itemNames) {
if (complexItems.any((item) => name.contains(item)))
complexity += 0.3;
if (simpleItems.any((item) => name.contains(item)))
complexity -= 0.1;
}
// Category diversity factor
final uniqueCategories = categories.toSet().length;
complexity += uniqueCategories * 0.1;
return complexity.clamp(0.0, 1.0);
}// Weighted priority scoring
static double _calculatePriorityScore(Map<String, dynamic> context) {
double priority = 0.0;
// Urgency factors (40% weight)
final maxUrgency = context['urgency_indicators'].values
.reduce((a, b) => a > b ? a : b);
priority += maxUrgency * 0.4;
// Value factors (25% weight)
final totalValue = context['value_analysis']['total_value'];
final valueScore = (totalValue / 1000.0).clamp(0.0, 1.0);
priority += valueScore * 0.25;
// Complexity factors (20% weight)
final complexity = context['complexity_score'];
priority += complexity * 0.2;
// Seasonal factors (10% weight)
final seasonalUrgency = context['seasonal_factors']['seasonal_urgency'];
priority += seasonalUrgency * 0.1;
// Quantity factors (5% weight)
final quantity = context['quantity_pattern'];
final quantityScore = (quantity / 20.0).clamp(0.0, 1.0);
priority += quantityScore * 0.05;
return priority.clamp(0.0, 1.0);
}// Multi-criteria decision matrix
static String _makeAIDecision(Map<String, dynamic> context, double priority) {
final urgencyScores = context['urgency_indicators'];
final valueAnalysis = context['value_analysis'];
final complexity = context['complexity_score'];
final totalValue = valueAnalysis['total_value'];
final itemDiversity = context['item_diversity'];
// High Priority Scenarios (Processing)
if (priority > 0.7) return 'processing';
if (urgencyScores.isNotEmpty) return 'processing';
if (totalValue > 500 && complexity > 0.3) return 'processing';
// Medium Priority Scenarios (Conditional Processing)
if (priority > 0.5 && complexity > 0.2) return 'processing';
if (totalValue > 200 && itemDiversity > 2) return 'processing';
// Low Priority Scenarios (Pending)
return 'pending';
}// Time-based urgency patterns
static Map<String, double> _detectSeasonalPatterns() {
final now = DateTime.now();
final month = now.month;
final dayOfWeek = now.weekday;
double seasonalUrgency = 0.0;
// Holiday seasons (higher urgency)
if (month == 12) seasonalUrgency += 0.3; // December
if (month == 11) seasonalUrgency += 0.2; // November
if (month == 2) seasonalUrgency += 0.1; // February
// Weekend orders (lower urgency)
if (dayOfWeek == 6 || dayOfWeek == 7) seasonalUrgency -= 0.1;
return {
'seasonal_urgency': seasonalUrgency,
'month_factor': month / 12.0,
'weekend_factor': (dayOfWeek == 6 || dayOfWeek == 7) ? 0.5 : 1.0,
};
}- Time Complexity: O(mΓn) for Levenshtein distance
- Space Complexity: O(mΓn) for dynamic programming matrix
- Typical Response Time: < 10ms for most queries
- Memory Usage: Minimal (temporary matrices)
- Time Complexity: O(n) where n is number of items
- Space Complexity: O(n) for context analysis
- Decision Time: < 5ms per order
- Scalability: Handles thousands of orders efficiently
- Early Termination: Stop processing when exact matches found
- Caching: Cache similarity scores for repeated comparisons
- Threshold Filtering: Skip low-probability matches early
- Indexed Search: Use database indexes for exact matches
- Fuzzy Matching: 95%+ accuracy for common typos
- Auto Status: 85%+ accuracy for appropriate status assignment
- False Positives: < 5% for high-threshold settings
- False Negatives: < 10% for balanced threshold settings
- customers: Customer information with ID, name, email, phone, address
- items: Product catalog with item codes, names, prices, categories
- orders: Order headers with customer references and totals
- order_items: Order line items with quantities and prices
- One-to-Many: Customer β Orders (one customer can have multiple orders)
- One-to-Many: Order β Order Items (one order can have multiple items)
- Many-to-One: Order Items β Items (items can be in multiple orders)
- Primary Keys: Unique identifiers for all entities
- Foreign Keys: Referential integrity between tables
- Indexes: Performance optimization on frequently queried fields
- Timestamps: Created and updated timestamps for audit trails
- JSONB Support: Flexible attributes storage for items
- SupabaseConfig.loadEnv(): Load environment variables from .env file
- SupabaseConfig.supabaseUrl: Get Supabase project URL
- SupabaseConfig.supabaseAnonKey: Get anonymous API key
- SupabaseConfig.isConfigured: Validate configuration completeness
- DatabaseService.initialize(): Initialize Supabase client
- DatabaseService.supabase: Get singleton Supabase client instance
- Supabase.instance.client: Access global Supabase client
- Row Level Security (RLS): Enabled on all tables
- Public Read Access: Allow reading data without authentication
- Authenticated Write Access: Require authentication for modifications
- Cascade Deletes: Automatic cleanup of related records
- ApiService.getOrders(): Fetch all orders with customer and item details
- ApiService.getOrderById(): Retrieve specific order by ID
- ApiService.createOrder(): Create new order with items
- ApiService.updateOrder(): Modify existing order details
- ApiService.deleteOrder(): Remove order and related items
- ApiService.searchOrders(): Search orders by various criteria
- ApiService.getItems(): Fetch all available items
- ApiService.getItemById(): Retrieve specific item by code
- ApiService.createItem(): Add new item to catalog
- ApiService.updateItem(): Modify item details
- ApiService.deleteItem(): Remove item from catalog
- ApiService.getCustomers(): Fetch all customer records
- ApiService.getCustomerById(): Retrieve specific customer by ID
- ApiService.createCustomer(): Add new customer
- ApiService.updateCustomer(): Modify customer information
- ApiService.deleteCustomer(): Remove customer record
- ApiService.clearDatabase(): Remove all data from tables
- ApiService.resetDatabase(): Clear and repopulate with sample data
- ApiService.recreateDatabase(): Full database recreation
- DatabaseService.getCustomers(): Query customers with ordering
- DatabaseService.getCustomerById(): Find customer by unique ID
- DatabaseService.insertCustomer(): Add new customer record
- DatabaseService.updateCustomer(): Modify existing customer
- DatabaseService.deleteCustomer(): Remove customer record
- DatabaseService.getItems(): Query items with name ordering
- DatabaseService.getItemById(): Find item by unique code
- DatabaseService.insertItem(): Add new item to catalog
- DatabaseService.updateItem(): Modify item details
- DatabaseService.deleteItem(): Remove item from catalog
- DatabaseService.getOrders(): Complex query with joins for customer and item data
- DatabaseService.getOrderById(): Retrieve specific order with full details
- DatabaseService.insertOrder(): Transaction to insert order and order items
- DatabaseService.updateOrder(): Update order and replace order items
- DatabaseService.deleteOrder(): Cascade delete order and related items
- DatabaseService.getOrderItems(): Fetch items for specific order
- DatabaseService.insertSampleData(): Populate database with test data
- DatabaseService.clearDatabase(): Remove all records safely
- GET /customers: Retrieve all customers
- GET /customers/{id}: Get specific customer by ID
- GET /items: Retrieve all items
- GET /items/{code}: Get specific item by code
- GET /orders: Retrieve all orders with related data
- GET /orders/{id}: Get specific order by ID
- GET /order_items/{orderId}: Get items for specific order
- POST /customers: Create new customer record
- POST /items: Add new item to catalog
- POST /orders: Create new order with items
- POST /order_items: Add items to existing order
- PUT /customers/{id}: Update customer information
- PUT /items/{code}: Modify item details
- PUT /orders/{id}: Update order and replace items
- DELETE /customers/{id}: Remove customer record
- DELETE /items/{code}: Remove item from catalog
- DELETE /orders/{id}: Remove order and related items
- UI Layer: User interaction triggers API call
- ApiService: Business logic and error handling
- DatabaseService: Direct Supabase client operations
- Supabase Client: HTTP requests to Supabase API
- PostgreSQL Database: Data storage and retrieval
- PostgreSQL Database: Query results and data
- Supabase API: JSON response formatting
- Supabase Client: Response parsing and error handling
- DatabaseService: Data transformation and model creation
- ApiService: Business logic validation
- UI Layer: Display updated data to user
- Network Errors: Connection timeout and retry logic
- Authentication Errors: Invalid API keys and permissions
- Validation Errors: Data format and constraint violations
- Business Logic Errors: Custom application error messages
- Indexed Queries: Fast lookups on frequently accessed fields
- Efficient Joins: Optimized queries for related data
- Connection Pooling: Reuse database connections
- Query Caching: Cache frequently accessed data
- Batch Operations: Multiple operations in single request
- Pagination: Limit result sets for large datasets
- Selective Fields: Only retrieve needed data
- Async Operations: Non-blocking database calls
- Singleton Pattern: Reuse database service instances
- Error Recovery: Graceful handling of connection issues
- Data Validation: Client-side validation before API calls
- Offline Support: Local caching for offline operations
- Order Creation: Create orders with multiple items and customer assignment
- Order Viewing: View all orders with customer and item details
- Order Editing: Modify existing orders, items, and status
- Order Deletion: Remove orders with automatic cleanup of related data
- Order Search: Search orders by item names using fuzzy matching
- Customer Creation: Add new customers with contact information
- Customer Viewing: View all customers with order history
- Customer Editing: Update customer details and contact information
- Customer Deletion: Remove customers (preserves order history)
- Item Creation: Add new items to the product catalog
- Item Viewing: Browse all items with categories and pricing
- Item Editing: Update item details, prices, and availability
- Item Deletion: Remove items from catalog
- Fuzzy Search: Intelligent search with typo tolerance
- Auto Status Assignment: AI-based order status assignment
- ERP Import: Import orders from flat files with fuzzy matching
- Email Notifications: Send order confirmations via Resend API
- Database Management: Clear, reset, and recreate database
- Supabase Database: PostgreSQL backend with proper relationships
- Real-time Updates: Live data synchronization
- Error Handling: Graceful error management and user feedback
- Data Validation: Input validation and data integrity checks
- No Pagination: All data loads at once (may be slow with large datasets)
- No Caching: Data is fetched fresh each time
- No Offline Mode: Requires internet connection
- No Batch Operations: Individual operations only
- Small to Medium Scale: Optimized for typical business volumes
- No Advanced Optimizations: Basic database queries without performance tuning
- Memory Usage: All data loaded into memory
- Basic UI: Functional but not highly polished
- No Advanced Filtering: Basic search only
- No Export Features: Data export not implemented
- No Bulk Operations: Individual item/order management only
- Small to Medium Businesses: 10-1000 orders per month
- Simple Order Management: Basic order tracking and customer management
- ERP Integration: Importing orders from existing systems
- Email Automation: Automated customer notifications
- Regular Backups: Use database reset features for data management
- Data Validation: Verify imported data before processing
- Email Configuration: Ensure Resend API is properly configured
- Fuzzy Matching: Adjust thresholds based on data quality
- Database Cleanup: Use clear/reset functions for data management
- Sample Data: Use insertSampleData for testing
- Error Monitoring: Check console logs for issues
- Configuration: Verify environment variables are set correctly
- Supabase project configured
- Environment variables set (SUPABASE_URL, SUPABASE_ANON_KEY)
- Resend API key configured (for email notifications)
- Database schema deployed
- Sample data loaded (optional)
- Order creation and editing
- Customer management
- Item catalog management
- Fuzzy search functionality
- ERP import process
- Email notification system
- Auto status assignment
- Database management functions
- Environment variables secured
- Database backups configured
- Error monitoring in place
- User training completed
- Data migration plan (if applicable)
- Data Not Loading: Check Supabase configuration and network connection
- Import Failures: Verify file format and fuzzy matching thresholds
- Email Errors: Check Resend API key and email configuration
- Performance Issues: Consider data volume and implement pagination if needed
- Technical Issues: Check console logs and error messages
- Configuration Help: Verify environment variables and API keys
- Feature Requests: Document requirements for future enhancements
- Pagination: For large datasets
- Advanced Filtering: Multi-criteria search and filtering
- Batch Operations: Bulk import/export capabilities
- Offline Support: Local data caching
- Performance Optimizations: Query caching and connection pooling
- Advanced UI: Enhanced user interface and experience
- Reporting: Data analytics and reporting features
- Mobile App: Native mobile application
- Database Optimization: Advanced indexing and query optimization
- Caching Layer: Redis or similar caching solution
- Load Balancing: Multiple server instances
- CDN Integration: Content delivery network for static assets
Note: This implementation provides a solid foundation for order management with all core functionality working. The system is production-ready for small to medium-scale operations, with clear paths for future enhancements as business needs grow.
- Frontend: Flutter (Dart) - Cross-platform framework
- Backend: Supabase (PostgreSQL database, Edge Functions)
- Hosting: Firebase Hosting
- Email Service: Resend (via Supabase Edge Function)
- Build System: Flutter Web with environment variable support
orderengine/
βββ lib/
β βββ main.dart # App entry point
β βββ models/ # Data models (Order, Customer, Item)
β βββ screens/ # UI screens
β β βββ order_list_screen.dart
β β βββ create_order_screen.dart
β β βββ order_detail_screen.dart
β β βββ database_management_screen.dart
β β βββ erp_import_screen.dart
β β βββ add_customer_screen.dart
β β βββ add_item_screen.dart
β βββ services/ # Business logic
β β βββ api_service.dart
β β βββ database_service.dart
β β βββ email_service.dart
β β βββ erp_import_service.dart
β βββ utils/ # Utilities
β β βββ constants.dart
β β βββ supabase_config.dart
β β βββ auto_status_assigner.dart
β β βββ fuzzy_matcher.dart
β βββ widgets/ # Reusable UI components
βββ web/ # Web-specific files
βββ test/ # Unit tests
βββ .env # Environment variables (not in repo)
βββ deploy.sh # Deployment script
βββ firebase.json # Firebase configuration
βββ .firebaserc # Firebase project settings
βββ README.md # This file
- Flutter SDK (latest stable version)
- Firebase CLI (
npm install -g firebase-tools) - Supabase Account & project
- Resend Account (for email notifications)
git clone <repository-url>
cd orderengineCreate a .env file in the project root (this file is not committed to git for security):
# Supabase Configuration
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-supabase-anon-key
# App Configuration
APP_NAME=Order Engine
APP_VERSION=1.0.0
# Database Configuration
DB_ENABLE_LOGGING=true
DB_TIMEOUT=30000Important: The Resend API key is stored securely in the Supabase Edge Function, not in the Flutter app.
flutter pub getflutter run -d chromeUse the provided deployment script:
./deploy.shThis script will:
- β
Check for
.envfile - π Load environment variables
- π¨ Build Flutter web app with environment variables
- π Deploy to Firebase Hosting
# Build with environment variables
flutter build web --release \
--dart-define=SUPABASE_URL="$SUPABASE_URL" \
--dart-define=SUPABASE_ANON_KEY="$SUPABASE_ANON_KEY"
# Deploy to Firebase
firebase deploy --only hostingYour app will be available at: https://order-engine-d3c69.web.app
| Variable | Description | Required | Location |
|---|---|---|---|
SUPABASE_URL |
Your Supabase project URL | Yes | .env file |
SUPABASE_ANON_KEY |
Your Supabase anonymous key | Yes | .env file |
APP_NAME |
Application name | No | .env file |
APP_VERSION |
Application version | No | .env file |
Security Note: The Resend API key is stored in the Supabase Edge Function environment, not in the frontend.
The app supports two approaches for environment configuration:
- Uses
flutter_dotenvpackage to load variables from.envfile - Good for development and flexible configuration
- File is included in assets and bundled with the app
- Uses hardcoded constants in
lib/utils/env.dart - Values are compiled into the APK during build time
- More secure for production builds
- No external file dependencies
To switch to Dart constants:
// In main.dart, before SupabaseConfig.loadEnv():
SupabaseConfig.useDartConstants();
await SupabaseConfig.loadEnv();Dart Constants File (lib/utils/env.dart):
class Env {
static const String supabaseUrl = 'https://your-project.supabase.co';
static const String supabaseAnonKey = 'your-anon-key';
static const String appName = 'Order Engine';
static const String appVersion = '1.0.0';
}Security Note: When using Dart constants, ensure
lib/utils/env.dartis added to.gitignoreto avoid committing sensitive data.
- Order Creation/Update: App calls Supabase Edge Function
- Email Processing: Edge Function uses Resend API to send emails
- Delivery: Customer receives order confirmation/update email
- Testing Mode: Only
[email protected]can receive emails - Production: Requires domain verification with Resend
- Fallback: App shows user-friendly messages when emails can't be sent
- Order Confirmation: Sent when new order is created
- Order Update: Sent when order status changes
- Test Email: Available in database management screen
ERP A Format (Pipe-delimited):
ORDER001|John Doe|20240601|LAPTOP001|1|1200.00|PENDING
ERP B Format (CSV):
ORDER001,CUST001,2024-06-01,LAPTOP001,1,1200.00,0
- Automatic Format Detection: Detects ERP A or ERP B format
- Fuzzy Item Matching: Matches item codes with typo tolerance
- Preview System: Review data before import
- Duplicate Detection: Prevents duplicate orders
- Error Handling: Graceful handling of invalid data
- Upload File: Select ERP data file
- Preview Data: Review parsed data and fuzzy matches
- Manual Review: Adjust any fuzzy matches if needed
- Execute Import: Import data to database
The system automatically assigns order status based on:
- Order Value: High-value orders get priority
- Item Types: Fragile items get special handling
- Customer History: Regular customers get faster processing
- Order Complexity: Multiple items may affect status
- Pending: Default status for new orders
- Processing: Orders being prepared
- Completed: Successfully delivered orders
- Cancelled: Cancelled orders
flutter test- ERP Import Service: Format detection, parsing, fuzzy matching
- Auto Status Assigner: Status assignment logic
- Fuzzy Matcher: String similarity algorithms
- Widget Tests: UI component testing
1. Environment Variables Not Loading
- Check
.envfile exists and has correct format - Verify no extra spaces in variable values
- Ensure
.envfile is in project root
2. Supabase Connection Issues
- Verify
SUPABASE_URLandSUPABASE_ANON_KEYare correct - Check Supabase project is active
- Verify database tables exist
3. Email Not Sending
- Check Supabase Edge Function is deployed
- Verify Resend API key in Edge Function
- Check email domain verification status
4. Build Errors
- Run
flutter cleanthenflutter pub get - Check Flutter version compatibility
- Verify all dependencies are installed
# Check environment variables
cat .env
# Test Supabase connection
flutter run -d chrome --debug
# View Firebase logs
firebase functions:log
# Check deployment status
firebase hosting:channel:list- Monthly: Review and rotate API keys
- Quarterly: Update Flutter and dependencies
- As Needed: Monitor Firebase and Supabase usage
- Firebase Console: Monitor hosting performance
- Supabase Dashboard: Monitor database usage
- Resend Dashboard: Monitor email delivery rates
To update the application:
- Code Changes: Make your changes
- Test Locally:
flutter run -d chrome - Deploy:
./deploy.sh - Verify: Test live application
- Live Application: https://order-engine-d3c69.web.app
- Firebase Console: https://console.firebase.google.com/project/order-engine-d3c69
- Supabase Dashboard: https://app.supabase.com
- Flutter Documentation: https://docs.flutter.dev
Q: How do I add new customers or items? A: Use the Database Management screen accessible from the main menu.
Q: Can I import data from other ERP systems? A: Yes, the system can be extended to support additional ERP formats.
Q: Why aren't emails being sent to all customers?
A: Currently only [email protected] can receive emails until domain verification is completed.
Q: How do I update the application?
A: Make your changes, test locally, then run ./deploy.sh to deploy.
Q: Is the data secure? A: Yes, all data is stored in Supabase with proper security measures and API keys are not exposed to the frontend.
For technical support or questions about this application, please contact your development team or project manager.
Last Updated: December 2024 Version: 1.0.0
- OrderListScreen: Primary dashboard and entry point
- CreateOrderScreen: Order creation and editing
- OrderDetailScreen: Detailed order view
- DatabaseManagementScreen: Data management with tabs
- ERPImportScreen: File import and processing
- AddItemScreen: Item creation
- AddCustomerScreen: Customer creation
- Order Display: List all orders with customer and item information
- Search & Filter: Fuzzy search by item names with real-time suggestions
- Quick Actions: Create new orders, import data, manage database
- Order Cards: Visual order representation with status indicators
- Floating Action Button: Create new order
- App Bar Actions:
- Refresh: Reload order data
- ERP Import: Navigate to import screen
- Database Management: Navigate to data management
- Fuzzy Matching: Intelligent search with typo tolerance
- Real-time Suggestions: Item suggestions as you type
- Clear Search: Easy search reset functionality
- Load Data: Automatically loads orders, items, and customers
- Search Orders: Type to filter by item names
- View Orders: Tap order cards for detailed view
- Create Order: Use FAB to add new orders
- Manage Data: Access database management tools
- Customer Selection: Choose from existing customers
- Item Addition: Add multiple items with quantities
- Auto Status Assignment: AI-based status determination
- Total Calculation: Automatic price calculations
- Email Notifications: Optional customer notifications
- Customer Field: Dropdown with existing customers
- Item Forms: Dynamic item addition/removal
- Quantity Controls: Numeric input with validation
- Status Field: Auto-assigned or manual selection
- Total Display: Real-time order total calculation
- High-Value Orders: Automatic "Processing" status
- Fragile Items: Special handling considerations
- Urgency Keywords: Priority based on item names
- Complex Orders: Multi-factor analysis
- Select Customer: Choose from dropdown or create new
- Add Items: Select items and set quantities
- Review Status: Check auto-assigned or manual status
- Calculate Total: Verify order amount
- Save Order: Create order with email notification
- Order Header: ID, customer, date, status, total
- Item List: Complete item details with quantities
- Customer Info: Contact and address information
- Status History: Order status changes
- Action Buttons: Edit, delete, email options
- Edit Order: Modify existing order details
- Delete Order: Remove order with confirmation
- Email Customer: Send status updates
- Status Updates: Change order status
- View Details: See complete order information
- Edit Order: Modify items, quantities, or status
- Send Notifications: Email customer updates
- Delete Order: Remove if needed
- Return to List: Navigate back to order list
- Items Tab: Product catalog management
- Customers Tab: Customer database management
- System Actions: Clear, reset, test functions
- Item List: View all products with details
- Add Items: Create new products
- Edit Items: Modify existing items
- Delete Items: Remove from catalog
- Search Items: Find specific products
- Customer List: View all customers
- Add Customers: Create new customer records
- Edit Customers: Update customer information
- Delete Customers: Remove customer records
- Email Testing: Test notification system
- Clear All Data: Remove all records
- Reset Database: Clear and reload sample data
- Test Email Service: Verify notification system
- Data Export: View data statistics
- Select Tab: Choose Items or Customers
- View Data: Browse existing records
- Add Records: Create new items/customers
- Edit Records: Modify existing data
- System Actions: Manage database operations
- File Upload: Select ERP files (CSV, pipe-delimited)
- Text Input: Paste content directly
- Format Detection: Automatic format recognition
- Preview Import: Review before processing
- Execute Import: Process and import data
- Fuzzy Threshold: Adjust matching sensitivity
- Create Missing Items: Auto-create new products
- Create Missing Customers: Auto-create new customers
- Skip Duplicates: Avoid duplicate orders
- Update Existing: Modify existing records
- Data Preview: Review imported records
- Fuzzy Matches: See item matching results
- Warnings: Identify potential issues
- Statistics: Import summary information
- Manual Mappings: Override automatic matches
- Upload File: Select ERP file or paste content
- Configure Options: Set import preferences
- Preview Data: Review import results
- Adjust Mappings: Fix any matching issues
- Execute Import: Process and import data
- Item Code: Unique product identifier
- Name: Product name
- Description: Detailed product description
- Price: Unit price with validation
- Category: Product categorization
- Availability: Stock status toggle
- Image URL: Optional product image
- Attributes: Additional product details
- Required Fields: Ensure essential data
- Price Validation: Positive number requirements
- Code Uniqueness: Prevent duplicate codes
- Format Validation: Proper data formats
- Fill Form: Enter item details
- Validate Data: Check for errors
- Save Item: Create new product
- Return to List: Navigate back to items
- Customer ID: Unique identifier
- Name: Customer full name
- Email: Contact email address
- Phone: Contact phone number
- Address: Physical address
- Validation: Data format checking
- Required Fields: Essential customer information
- Email Validation: Proper email format
- Phone Validation: Contact number format
- ID Uniqueness: Prevent duplicate IDs
- Enter Details: Fill customer information
- Validate Data: Check for errors
- Save Customer: Create new customer
- Return to List: Navigate back to customers
- Start: OrderListScreen (home)
- Create Order: OrderListScreen β CreateOrderScreen
- View Details: OrderListScreen β OrderDetailScreen
- Manage Data: OrderListScreen β DatabaseManagementScreen
- Import Data: OrderListScreen β ERPImportScreen
- Add Items: DatabaseManagementScreen β AddItemScreen
- Add Customers: DatabaseManagementScreen β AddCustomerScreen
- Edit Orders: OrderDetailScreen β CreateOrderScreen
- Forward Navigation: Create new data or view details
- Back Navigation: Return to previous screens
- Tab Navigation: Switch between data types
- Modal Dialogs: Quick actions and confirmations
- Material Design 3: Modern Flutter design
- Light/Dark Themes: Automatic theme switching
- Consistent Styling: Unified visual language
- Responsive Layout: Adapts to different screen sizes
- Floating Action Buttons: Primary actions
- Search Bars: Intelligent filtering
- Cards: Information containers
- Lists: Data presentation
- Forms: Data input and validation
- Loading Indicators: Progress feedback
- Success Messages: Confirmation notifications
- Error Handling: Clear error messages
- Status Indicators: Visual status representation
- Large Touch Targets: Easy button interaction
- Swipe Gestures: Intuitive navigation
- Scroll Support: Smooth scrolling lists
- Keyboard Handling: Proper input management
- Fast Loading: Optimized data loading
- Smooth Animations: Fluid transitions
- Responsive UI: Quick user feedback
- Offline Considerations: Graceful error handling