Cursor rule
.cursor/rules/business-logic-patterns.mdcComprehensive business logic patterns for POS System domain understanding, user journeys, and workflow optimization
Cursor rules
Quality
50/100
Scores the file, not the repository.Length
3,136 words
24 headings · 15 code blocksRepository
118
— · pushed 339 days agoLast changed
3 days ago
First indexed 3 days ago.12345# 🍽️ POS Business Logic & Domain Patterns67## 🎯 Core Business Domain Understanding89### Restaurant Operations Model10The POS system orchestrates complex restaurant operations with multiple stakeholders and intricate workflows:1112```typescript13// Domain Model - Core Business Entities14interface RestaurantDomain {15 // Revenue Generation16 orders: OrderLifecycle[]17 payments: PaymentProcessing[]18 inventory: InventoryManagement1920 // Operations Management21 tables: TableManagement22 staff: StaffOperations23 kitchen: KitchenWorkflow2425 // Business Intelligence26 analytics: BusinessAnalytics27 reporting: FinancialReporting28}2930// Business Rules Engine31class POSBusinessRules {32 validateOrderCreation(order: CreateOrderRequest): ValidationResult33 calculatePricing(items: OrderItem[]): PricingCalculation34 manageInventory(productId: string, quantity: number): InventoryResult35 optimizeKitchenWorkflow(orders: Order[]): WorkflowOptimization36}37```3839## 🔄 Critical User Journeys & Performance Optimization4041### 1. Server Journey: Dine-In Order Creation (Target: <30 seconds)42```typescript43// ✅ PERFORMANCE-OPTIMIZED: Server workflow44class ServerWorkflowOptimization {45 // Pre-load critical data for instant access46 private async preloadServerData(): Promise<ServerContext> {47 const [products, categories, tables, activeOrders] = await Promise.all([48 this.productService.getAvailableProducts(), // Cache for 5 minutes49 this.categoryService.getActiveCategories(), // Cache for 1 hour50 this.tableService.getTableStatus(), // Real-time, 30s cache51 this.orderService.getActiveOrders() // Real-time, 10s cache52 ])5354 return { products, categories, tables, activeOrders }55 }5657 // Optimistic order creation with rollback58 async createOrderOptimistic(orderData: CreateOrderRequest): Promise<Order> {59 // 1. Immediate UI feedback (0ms)60 this.ui.showOrderCreating(orderData)6162 // 2. Validate business rules locally (5-10ms)63 const validation = await this.validateOrderBusiness(orderData)64 if (!validation.isValid) {65 throw new BusinessRuleError(validation.errors)66 }6768 // 3. Optimistic update (10-15ms)69 const optimisticOrder = this.generateOptimisticOrder(orderData)70 this.ui.showOrderCreated(optimisticOrder)7172 // 4. Background server sync (100-200ms)73 try {74 const serverOrder = await this.orderService.createOrder(orderData)75 this.reconcileOptimisticOrder(optimisticOrder, serverOrder)76 return serverOrder77 } catch (error) {78 // Rollback optimistic changes79 this.rollbackOptimisticOrder(optimisticOrder)80 throw error81 }82 }8384 // Business rule validation (prevent API round-trips)85 private async validateOrderBusiness(order: CreateOrderRequest): Promise<ValidationResult> {86 const errors: string[] = []8788 // Table availability check89 if (order.table_id && !this.isTableAvailable(order.table_id)) {90 errors.push('Table is not available')91 }9293 // Product availability batch check94 const unavailableItems = order.items.filter(item =>95 !this.isProductAvailable(item.product_id, item.quantity)96 )97 if (unavailableItems.length > 0) {98 errors.push(`Products unavailable: ${unavailableItems.map(i => i.product_id).join(', ')}`)99 }100101 // Business hours validation102 if (!this.isDuringBusinessHours()) {103 errors.push('Orders cannot be created outside business hours')104 }105106 return { isValid: errors.length === 0, errors }107 }108}109```110111### 2. Enhanced Kitchen Journey: As-Ready Service Workflow (Target: <3 seconds per item update)112```typescript113// ✅ REAL-TIME OPTIMIZED: Enhanced kitchen workflow with individual item tracking114class EnhancedKitchenWorkflowEngine {115 private orderPriorityQueue: PriorityQueue<KitchenOrder>116 private preparationTimers: Map<string, Timer>117 private realTimeUpdates: EventEmitter118 private soundNotificationSystem: SoundNotificationSystem119120 // Intelligent order prioritization with as-ready service121 async optimizeKitchenQueue(): Promise<KitchenOrder[]> {122 const activeOrders = await this.getActiveKitchenOrders()123124 // Business logic: Priority calculation with individual item tracking125 return activeOrders126 .map(order => ({127 ...order,128 priority: this.calculateOrderPriority(order),129 estimatedTime: this.estimatePreparationTime(order),130 dependencies: this.findOrderDependencies(order),131 itemProgress: this.calculateItemProgress(order.items), // New: Individual item tracking132 readyItems: order.items.filter(item => item.status === 'ready'),133 servedItems: order.items.filter(item => item.status === 'served')134 }))135 .sort((a, b) => {136 // Enhanced priority: wait time, complexity, table status, ready items137 const aScore = (a.priority * a.waitTime * a.tableUrgency) + (a.readyItems.length * 10)138 const bScore = (b.priority * b.waitTime * b.tableUrgency) + (b.readyItems.length * 10)139 return bScore - aScore140 })141 }142143 // As-ready service: Individual item completion144 async markItemReady(orderId: string, itemId: string): Promise<void> {145 await this.updateItemStatus(orderId, itemId, 'ready')146 this.soundNotificationSystem.playItemReadySound() // 1200Hz beep147 this.notifyCounterStaff(orderId, itemId)148 }149150 // As-ready service: Individual item serving151 async serveReadyItem(orderId: string, itemId: string): Promise<void> {152 await this.updateItemStatus(orderId, itemId, 'served')153 this.soundNotificationSystem.playItemServedSound() // 1400Hz beep154155 // Check if entire order is complete156 const order = await this.getOrder(orderId)157 if (this.isOrderFullyServed(order)) {158 await this.completeOrder(orderId)159 this.removeFromKitchenDisplay(orderId)160 }161 }162163 // Real-time status updates with business impact164 async updateOrderStatus(orderId: string, status: KitchenStatus): Promise<void> {165 const order = await this.getOrder(orderId)166 const businessImpact = await this.calculateBusinessImpact(order, status)167168 // Update with business context169 await this.orderService.updateOrderStatus(orderId, {170 status,171 estimated_completion: businessImpact.estimatedCompletion,172 kitchen_notes: businessImpact.notes,173 affects_other_orders: businessImpact.dependencies174 })175176 // Trigger real-time notifications177 this.notifyStakeholders(order, status, businessImpact)178179 // Update kitchen display optimization180 this.reoptimizeKitchenQueue()181 }182183 // Business intelligence: Kitchen performance metrics184 private calculateBusinessImpact(order: Order, newStatus: KitchenStatus): BusinessImpact {185 return {186 tableWaitTime: this.calculateTableWaitTime(order.table_id),187 kitchenEfficiency: this.calculateKitchenEfficiency(),188 customerSatisfactionImpact: this.predictSatisfactionImpact(order, newStatus),189 revenueImpact: this.calculateRevenueImpact(order, newStatus),190 staffWorkloadImpact: this.calculateWorkloadImpact(newStatus)191 }192 }193}194```195196### 3. Counter Journey: Payment Processing (Target: <10 seconds)197```typescript198// ✅ PAYMENT-OPTIMIZED: Multi-step payment with error handling199class PaymentWorkflowEngine {200 // Payment processing with comprehensive business validation201 async processPayment(paymentRequest: PaymentRequest): Promise<PaymentResult> {202 // 1. Pre-flight validation (instant)203 const validation = await this.validatePaymentBusiness(paymentRequest)204 if (!validation.isValid) {205 throw new PaymentValidationError(validation.errors)206 }207208 // 2. Calculate final amounts with business rules209 const calculation = await this.calculatePaymentAmounts(paymentRequest)210211 // 3. Process payment with error handling212 try {213 const result = await this.executePayment(calculation)214215 // 4. Update business state216 await this.updateBusinessState(result)217218 // 5. Generate receipt and analytics219 await this.generateReceiptAndAnalytics(result)220221 return result222 } catch (error) {223 await this.handlePaymentError(error, paymentRequest)224 throw error225 }226 }227228 // Business-aware payment validation229 private async validatePaymentBusiness(request: PaymentRequest): Promise<ValidationResult> {230 const order = await this.orderService.getOrder(request.order_id)231 const errors: string[] = []232233 // Order state validation234 if (!['ready', 'served'].includes(order.status)) {235 errors.push('Order must be ready or served before payment')236 }237238 // Amount validation with business rules239 const expectedTotal = await this.calculateOrderTotal(order)240 if (Math.abs(request.amount - expectedTotal) > 0.01) {241 errors.push(`Payment amount ${request.amount} does not match order total ${expectedTotal}`)242 }243244 // Business hours and policies245 if (request.payment_method === 'check' && !this.acceptsChecks()) {246 errors.push('Check payments not accepted during this period')247 }248249 // Tip validation for business rules250 if (request.tip_amount && request.tip_amount > expectedTotal * 0.3) {251 errors.push('Tip amount seems unusually high, please confirm')252 }253254 return { isValid: errors.length === 0, errors }255 }256257 // Advanced payment calculation with business intelligence258 private async calculatePaymentAmounts(request: PaymentRequest): Promise<PaymentCalculation> {259 const order = await this.orderService.getOrderWithItems(request.order_id)260261 return {262 subtotal: this.calculateSubtotal(order.items),263 tax: this.calculateTax(order.items), // Business-specific tax rules264 discounts: await this.calculateDiscounts(order), // Loyalty, promotions265 serviceCharge: this.calculateServiceCharge(order), // Table service, large parties266 tip: request.tip_amount || 0,267 finalTotal: this.calculateFinalTotal(order, request),268 paymentBreakdown: this.generatePaymentBreakdown(request)269 }270 }271}272```273274## 🏗️ Tech Debt Prevention Patterns275276### 1. Consistency Enforcement277```typescript278// ✅ CONSISTENT: Standardized patterns across the system279namespace POSConsistency {280 // API Response consistency281 export interface StandardAPIResponse<T> {282 success: boolean283 message: string284 data?: T285 error?: string286 timestamp: string287 request_id: string // For debugging and tracing288 }289290 // Error handling consistency291 export class BusinessError extends Error {292 code: string293 userMessage: string294 context: Record<string, any>295296 constructor(code: string, message: string, userMessage: string, context?: Record<string, any>) {297 super(message)298 this.code = code299 this.userMessage = userMessage300 this.context = context || {}301 }302 }303304 // State management consistency305 export interface BaseEntityState<T> {306 items: T[]307 loading: boolean308 error: string | null309 lastUpdated: Date310 optimisticUpdates: Map<string, T>311 }312}313```314315### 2. DRY Principle Enforcement316```typescript317// ✅ DRY: Reusable business logic components318class ReusableBusinessComponents {319 // Unified validation system320 static createValidator<T>(schema: ValidationSchema<T>) {321 return {322 validate: (data: T): ValidationResult => {323 const errors: string[] = []324325 Object.entries(schema.rules).forEach(([field, rules]) => {326 const value = data[field]327 rules.forEach(rule => {328 if (!rule.check(value)) {329 errors.push(rule.message)330 }331 })332 })333334 return { isValid: errors.length === 0, errors }335 }336 }337 }338339 // Unified caching system340 static createCacheManager<T>(config: CacheConfig) {341 const cache = new Map<string, CacheEntry<T>>()342343 return {344 get: async (key: string, fetcher: () => Promise<T>): Promise<T> => {345 const cached = cache.get(key)346 if (cached && cached.expiresAt > Date.now()) {347 return cached.data348 }349350 const data = await fetcher()351 cache.set(key, {352 data,353 expiresAt: Date.now() + config.ttl,354 createdAt: Date.now()355 })356357 return data358 },359360 invalidate: (key: string) => cache.delete(key),361 clear: () => cache.clear()362 }363 }364365 // Unified state management366 static createStateManager<T>(initialState: T) {367 const subscribers = new Set<(state: T) => void>()368 let currentState = { ...initialState }369370 return {371 getState: () => currentState,372 setState: (updater: (state: T) => T) => {373 const newState = updater(currentState)374 currentState = newState375 subscribers.forEach(callback => callback(newState))376 },377 subscribe: (callback: (state: T) => void) => {378 subscribers.add(callback)379 return () => subscribers.delete(callback)380 }381 }382 }383}384```385386## ⚡ Performance-First Development Patterns387388### 1. Database Performance Optimization389```go390// ✅ PERFORMANCE: Intelligent query optimization with business understanding391type QueryOptimizer struct {392 db *sql.DB393 queryCache *QueryCache394 performanceMetrics *PerformanceMetrics395}396397// Business-aware query optimization398func (q *QueryOptimizer) GetOrdersOptimized(ctx context.Context, params OrderQueryParams) (*OrdersResult, error) {399 // 1. Query planning based on business patterns400 queryPlan := q.createQueryPlan(params)401402 // 2. Use business-specific indexes403 query := `404 SELECT405 o.id, o.order_number, o.status, o.created_at, o.total_amount,406 u.username, u.role,407 t.table_number, t.section,408 COUNT(oi.id) as item_count,409 -- Performance: Calculate totals in DB, not application410 SUM(oi.quantity * oi.price) as calculated_total411 FROM orders o412 -- Performance: Use covering indexes413 LEFT JOIN users u ON o.user_id = u.id414 LEFT JOIN dining_tables t ON o.table_id = t.id415 LEFT JOIN order_items oi ON o.id = oi.order_id416 WHERE 1=1417 `418419 args := []interface{}{}420 argIndex := 1421422 // Business-aware filtering423 if params.Status != "" {424 query += fmt.Sprintf(" AND o.status = $%d", argIndex)425 args = append(args, params.Status)426 argIndex++427 }428429 if params.DateRange.IsValid() {430 query += fmt.Sprintf(" AND o.created_at BETWEEN $%d AND $%d", argIndex, argIndex+1)431 args = append(args, params.DateRange.Start, params.DateRange.End)432 argIndex += 2433 }434435 // Performance: Smart pagination with business context436 if params.UserRole == "kitchen" {437 // Kitchen sees only orders that need preparation438 query += " AND o.status IN ('pending', 'confirmed', 'preparing')"439 query += " ORDER BY o.priority DESC, o.created_at ASC" // Urgency first440 } else {441 query += " ORDER BY o.created_at DESC"442 }443444 query += fmt.Sprintf(" GROUP BY o.id, u.username, u.role, t.table_number, t.section")445 query += fmt.Sprintf(" LIMIT $%d OFFSET $%d", argIndex, argIndex+1)446 args = append(args, params.Limit, params.Offset)447448 // Execute with performance monitoring449 start := time.Now()450 rows, err := q.db.QueryContext(ctx, query, args...)451 duration := time.Since(start)452453 // Business intelligence: Track query performance454 q.performanceMetrics.RecordQuery("get_orders", duration, len(args))455456 if duration > 100*time.Millisecond {457 log.Printf("SLOW QUERY WARNING: get_orders took %v", duration)458 }459460 return q.processOrderResults(rows)461}462```463464### 2. Frontend Performance with Business Intelligence465```typescript466// ✅ PERFORMANCE: Intelligent component optimization with business understanding467class BusinessIntelligentComponents {468 // Smart memoization based on business context469 static createSmartMemo<T extends ComponentProps>(470 Component: React.FC<T>,471 businessContext: BusinessContext472 ): React.FC<T> {473 return React.memo(Component, (prevProps, nextProps) => {474 // Business-aware comparison475 if (businessContext.isHighFrequencyUpdate) {476 // Kitchen orders update frequently - check only critical props477 return (478 prevProps.id === nextProps.id &&479 prevProps.status === nextProps.status &&480 prevProps.priority === nextProps.priority481 )482 } else {483 // Admin data changes less frequently - deep comparison ok484 return isEqual(prevProps, nextProps)485 }486 })487 }488489 // Intelligent data prefetching based on user journey490 static createDataPrefetcher(userRole: UserRole) {491 const prefetchStrategy = {492 admin: {493 prefetchOnIdle: ['reports', 'analytics', 'staff-performance'],494 preloadCritical: ['active-orders', 'system-status'],495 cacheStrategy: 'aggressive' // Admin needs comprehensive data496 },497 server: {498 prefetchOnIdle: ['menu-items', 'table-status'],499 preloadCritical: ['available-tables', 'active-categories'],500 cacheStrategy: 'moderate' // Balance speed vs memory501 },502 kitchen: {503 prefetchOnIdle: [],504 preloadCritical: ['pending-orders', 'preparation-queue'],505 cacheStrategy: 'minimal' // Real-time data, minimal cache506 }507 }508509 return prefetchStrategy[userRole]510 }511}512```513514## 🧪 QA Integration & Error Prevention515516### 1. Business Logic Testing Patterns517```typescript518// ✅ QA: Business logic testing with domain understanding519describe('POS Business Logic Tests', () => {520 describe('Order Creation Business Rules', () => {521 it('should prevent order creation outside business hours', async () => {522 // Given: Restaurant is closed523 const mockTime = new Date('2024-01-01T02:00:00') // 2 AM524 jest.setSystemTime(mockTime)525526 // When: Server attempts to create order527 const orderRequest = createMockOrderRequest({528 order_type: 'dine_in',529 items: [{ product_id: 'burger-1', quantity: 1 }]530 })531532 // Then: Should reject with business rule error533 await expect(orderService.createOrder(orderRequest))534 .rejects535 .toThrow(BusinessRuleError)536 .toMatchBusinessRule('OUTSIDE_BUSINESS_HOURS')537 })538539 it('should calculate complex pricing with discounts and tax', async () => {540 // Given: Order with loyalty discount and special tax rules541 const customer = createMockCustomer({ loyaltyTier: 'gold' })542 const orderItems = [543 { product_id: 'burger-1', quantity: 2, price: 12.99 },544 { product_id: 'drink-1', quantity: 2, price: 3.99 }545 ]546547 // When: Calculate final pricing548 const pricing = await pricingService.calculateOrderTotal({549 items: orderItems,550 customer,551 appliedPromotions: ['GOLD_10_PERCENT']552 })553554 // Then: Should apply business rules correctly555 expect(pricing).toMatchBusinessCalculation({556 subtotal: 33.96,557 discount: 3.40, // 10% gold discount558 tax: 2.75, // 9% tax after discount559 total: 33.31560 })561 })562 })563564 describe('Kitchen Workflow Business Rules', () => {565 it('should prioritize orders based on business intelligence', async () => {566 // Given: Multiple orders with different priorities567 const orders = [568 createMockOrder({ table_id: 'vip-1', wait_time: 15, complexity: 'high' }),569 createMockOrder({ table_id: 'regular-1', wait_time: 25, complexity: 'low' }),570 createMockOrder({ table_id: 'regular-2', wait_time: 10, complexity: 'medium' })571 ]572573 // When: Kitchen optimizes queue574 const optimizedQueue = await kitchenService.optimizeOrderQueue(orders)575576 // Then: Should prioritize based on business rules577 expect(optimizedQueue).toMatchBusinessPriority([578 'vip-1', // VIP table trumps wait time579 'regular-2', // Shorter wait time + medium complexity580 'regular-1' // Longest wait but easiest to complete581 ])582 })583 })584})585586// Custom Jest matchers for business logic587expect.extend({588 toMatchBusinessRule(received: Error, expectedRule: string) {589 const pass = received instanceof BusinessRuleError && received.code === expectedRule590 return {591 message: () => `Expected business rule ${expectedRule}, got ${received.constructor.name}`,592 pass593 }594 },595596 toMatchBusinessCalculation(received: PricingResult, expected: PricingExpectation) {597 const toleranceChecks = Object.entries(expected).every(([key, value]) => {598 const actual = received[key]599 return Math.abs(actual - value) < 0.01 // Penny tolerance for financial calculations600 })601602 return {603 message: () => `Business calculation mismatch: expected ${JSON.stringify(expected)}, got ${JSON.stringify(received)}`,604 pass: toleranceChecks605 }606 }607})608```609610### 2. Error Prevention with Business Context611```typescript612// ✅ ERROR PREVENTION: Comprehensive error handling with business intelligence613class BusinessErrorPrevention {614 // Intelligent error recovery based on business impact615 static createErrorRecoveryManager(businessContext: BusinessContext) {616 return {617 handleOrderError: async (error: Error, orderContext: OrderContext) => {618 const businessImpact = this.assessBusinessImpact(error, orderContext)619620 switch (businessImpact.severity) {621 case 'critical':622 // Revenue-affecting errors - immediate escalation623 await this.notifyManagement(error, orderContext)624 await this.createEmergencyBackup()625 return this.initiateFailsafeMode(orderContext)626627 case 'high':628 // Customer-affecting errors - graceful degradation629 await this.notifyStaff(error, orderContext)630 return this.provideFallbackService(orderContext)631632 case 'medium':633 // Performance errors - log and continue634 this.logBusinessError(error, orderContext)635 return this.retryWithBackoff(orderContext)636637 case 'low':638 // Minor errors - silent recovery639 return this.silentRecover(orderContext)640 }641 },642643 assessBusinessImpact: (error: Error, context: OrderContext): BusinessImpactAssessment => {644 // Business intelligence for error severity645 const factors = {646 revenueImpact: this.calculateRevenueAtRisk(context),647 customerImpact: this.calculateCustomerExperienceImpact(context),648 operationalImpact: this.calculateOperationalDisruption(context),649 timeOfDay: this.getBusinessPeriodSeverity(),650 staffAvailability: this.getStaffAvailabilityFactor()651 }652653 return this.computeBusinessSeverity(factors)654 }655 }656 }657658 // Proactive error prevention659 static createPreventiveHealthChecks() {660 return {661 // Business-critical system health662 checkOrderSystemHealth: async (): Promise<HealthCheck> => {663 const checks = await Promise.all([664 this.checkDatabasePerformance(), // Order creation speed665 this.checkPaymentGateway(), // Payment processing666 this.checkKitchenConnectivity(), // Kitchen display updates667 this.checkInventorySync(), // Product availability668 this.checkTableManagement() // Table status accuracy669 ])670671 return this.aggregateHealthStatus(checks)672 },673674 // Predictive failure detection675 detectPotentialFailures: async (): Promise<PredictiveAlert[]> => {676 const alerts: PredictiveAlert[] = []677678 // Database performance degradation679 if (await this.isDatabaseSlowing()) {680 alerts.push({681 type: 'database_performance',682 severity: 'warning',683 businessImpact: 'Order creation may slow down',684 recommendedAction: 'Consider scaling database resources'685 })686 }687688 // Kitchen queue overload689 const kitchenLoad = await this.getKitchenQueueLoad()690 if (kitchenLoad > 0.8) {691 alerts.push({692 type: 'kitchen_overload',693 severity: 'high',694 businessImpact: 'Customer wait times will increase',695 recommendedAction: 'Alert kitchen manager to optimize workflow'696 })697 }698699 return alerts700 }701 }702 }703}704```705706## 📊 Business Intelligence Integration707708### 1. Performance Monitoring with Business Context709```typescript710// ✅ BUSINESS INTELLIGENCE: Performance monitoring with business insights711class BusinessIntelligenceMonitoring {712 // Revenue-aware performance tracking713 static trackBusinessMetrics(operation: string, duration: number, businessContext: BusinessContext): void {714 const metrics = {715 operation,716 duration,717 timestamp: Date.now(),718719 // Business context720 revenueImpact: businessContext.calculateRevenueImpact(duration),721 customerImpact: businessContext.calculateCustomerImpact(duration),722 operationalEfficiency: businessContext.calculateEfficiency(duration),723724 // Performance classification725 performanceGrade: this.classifyPerformance(operation, duration),726 businessCriticality: this.assessBusinessCriticality(operation, businessContext)727 }728729 // Real-time business alerts730 if (metrics.revenueImpact > 100) { // $100+ revenue at risk731 this.sendBusinessAlert(`High revenue impact detected: ${operation} took ${duration}ms`)732 }733734 // Performance optimization recommendations735 if (metrics.performanceGrade === 'poor') {736 this.generateOptimizationRecommendation(metrics)737 }738 }739740 // Business-intelligent caching strategy741 static createBusinessCache<T>() {742 return {743 // Cache strategy based on business value744 set: (key: string, value: T, businessContext: BusinessContext) => {745 const ttl = this.calculateOptimalTTL(key, businessContext)746 const priority = this.calculateCachePriority(key, businessContext)747748 return this.cache.set(key, value, { ttl, priority })749 },750751 // Intelligent cache invalidation752 invalidateByBusinessEvent: (event: BusinessEvent) => {753 const affectedKeys = this.getAffectedCacheKeys(event)754 affectedKeys.forEach(key => this.cache.invalidate(key))755 }756 }757 }758}759```760761## 📱 Mobile Application Patterns (React Native)762763### 1. Kitchen Staff Mobile App - Tablet & TV Display Optimization764```typescript765// ✅ MOBILE-OPTIMIZED: Kitchen display for tablets and large screens766class MobileKitchenWorkflow {767 // Touch-optimized interface patterns768 private touchTargetSize = 50 // Minimum 50px for tablet touch769 private gestureHandlers: GestureHandlerManager770 private screenOrientation: 'landscape' | 'portrait'771772 // Large screen TV display mode773 async initializeTVDisplayMode(): Promise<void> {774 this.screenOrientation = 'landscape'775 this.enableAutoRotation(false)776 this.setFullScreenMode(true)777 this.optimizeForDistance(true) // Larger fonts, higher contrast778779 // TV-specific optimizations780 await this.configureDisplaySettings({781 fontSize: 'extra-large',782 contrast: 'high',783 colorScheme: 'high-visibility',784 touchTargets: 'extra-large' // 60px+ for wall-mounted displays785 })786 }787788 // Tablet-specific optimizations789 async initializeTabletMode(): Promise<void> {790 this.enableGestureNavigation()791 this.optimizeForHandheld(true)792793 // Tablet-specific features794 await this.configureTabletSettings({795 swipeGestures: true,796 pinchToZoom: false, // Prevent accidental zooming797 hapticFeedback: true,798 orientationLock: 'landscape-primary'799 })800 }801802 // Offline mode for kitchen operations803 async enableOfflineMode(): Promise<void> {804 await this.syncCriticalData() // Orders, menu items, status updates805 this.enableLocalStorage()806 this.setupOfflineQueue() // Queue updates for when connection returns807808 // Offline-first architecture809 this.dataManager.setPriority('local-first')810 this.notificationManager.enableLocalNotifications()811 }812}813```814815### 2. Server Group Mobile App - Smartphone & Tablet Flexibility816```typescript817// ✅ MOBILE-OPTIMIZED: Server workflow for smartphones and tablets818class MobileServerWorkflow {819 private deviceType: 'smartphone' | 'tablet'820 private paymentIntegration: MobilePaymentProcessor821822 // Adaptive UI based on device size823 async initializeDeviceOptimization(): Promise<void> {824 this.deviceType = await this.detectDeviceType()825826 if (this.deviceType === 'smartphone') {827 await this.optimizeForSmartphone()828 } else {829 await this.optimizeForTablet()830 }831 }832833 // Smartphone-specific optimizations834 private async optimizeForSmartphone(): Promise<void> {835 this.ui.setLayout('single-column')836 this.ui.enableBottomNavigation()837 this.ui.setTouchTargets('standard') // 44px minimum838839 // One-handed operation support840 this.ui.enableReachabilityMode()841 this.ui.setQuickActions(['add-item', 'view-cart', 'process-payment'])842 }843844 // Tablet-specific optimizations845 private async optimizeForTablet(): Promise<void> {846 this.ui.setLayout('multi-column')847 this.ui.enableSideNavigation()848 this.ui.setTouchTargets('large') // 50px for tablet use849850 // Multi-tasking support851 this.ui.enableSplitView() // Menu + cart simultaneously852 this.ui.setAdvancedGestures(true)853 }854855 // Mobile payment processing856 async processMobilePayment(amount: number, method: PaymentMethod): Promise<PaymentResult> {857 // Integration with mobile card readers858 if (method === 'card') {859 return await this.paymentIntegration.processCardPayment(amount)860 }861862 // NFC/contactless payments863 if (method === 'contactless') {864 return await this.paymentIntegration.processNFCPayment(amount)865 }866867 // Mobile wallet integration868 if (method === 'mobile_wallet') {869 return await this.paymentIntegration.processMobileWallet(amount)870 }871 }872}873```874875### 3. Cross-Platform Synchronization Patterns876```typescript877// ✅ SYNC-OPTIMIZED: Real-time synchronization between web and mobile878class CrossPlatformSyncManager {879 private webSocketConnection: WebSocketManager880 private offlineQueue: OfflineOperationQueue881 private conflictResolver: DataConflictResolver882883 // Real-time data synchronization884 async initializeCrossPlatformSync(): Promise<void> {885 // Establish WebSocket connection for real-time updates886 await this.webSocketConnection.connect()887888 // Listen for cross-platform events889 this.webSocketConnection.on('order-updated', this.handleOrderUpdate)890 this.webSocketConnection.on('kitchen-status-changed', this.handleKitchenUpdate)891 this.webSocketConnection.on('payment-processed', this.handlePaymentUpdate)892893 // Sync offline operations when connection restored894 this.webSocketConnection.on('reconnected', this.syncOfflineOperations)895 }896897 // Handle data conflicts between platforms898 async resolveDataConflicts(localData: any, serverData: any): Promise<any> {899 // Business rules for conflict resolution900 const resolution = await this.conflictResolver.resolve({901 local: localData,902 server: serverData,903 strategy: 'server-wins-for-payments', // Critical business rule904 fallback: 'merge-non-conflicting'905 })906907 return resolution.resolvedData908 }909910 // Offline operation queuing911 async queueOfflineOperation(operation: OfflineOperation): Promise<void> {912 await this.offlineQueue.add({913 ...operation,914 timestamp: Date.now(),915 deviceId: await this.getDeviceId(),916 priority: this.calculateOperationPriority(operation)917 })918 }919}920```921922## 🎯 Mobile Development Best Practices923924### Performance Optimization for Mobile925```typescript926// Mobile-specific performance patterns927class MobilePerformanceOptimizer {928 // Battery-conscious background processing929 async optimizeBatteryUsage(): Promise<void> {930 // Reduce polling frequency when app is backgrounded931 this.dataSync.setBackgroundPollingInterval(30000) // 30s instead of 5s932933 // Pause non-critical animations934 this.ui.pauseDecoractiveAnimations()935936 // Optimize network requests937 this.api.enableRequestBatching()938 this.api.setConnectionPooling(true)939 }940941 // Memory management for long-running kitchen displays942 async optimizeMemoryUsage(): Promise<void> {943 // Limit order history in memory944 this.orderManager.setMaxHistoryItems(50)945946 // Lazy load images and assets947 this.assetManager.enableLazyLoading()948949 // Garbage collection optimization950 this.schedulePeriodicCleanup(300000) // Every 5 minutes951 }952953 // Network optimization for mobile connections954 async optimizeNetworkUsage(): Promise<void> {955 // Compress API responses956 this.api.enableCompression()957958 // Cache frequently accessed data959 this.cache.setStrategy('aggressive-mobile')960961 // Implement smart retry logic962 this.api.setRetryStrategy({963 maxRetries: 3,964 backoffMultiplier: 2,965 networkAware: true // Adjust based on connection quality966 })967 }968}969```970971This comprehensive business logic pattern ensures your POS system truly understands the restaurant domain, optimizes for real business outcomes, prevents technical debt, and maintains the highest quality standards. The patterns now include mobile-first development approaches that align with the GitHub milestones for React Native kitchen and server applications. The patterns are designed to work together to create a cohesive, high-performance system that scales across web and mobile platforms.972973<function_calls>974<invoke name="todo_write">975<parameter name="merge">true
Also in madebyaris/poinf-of-sales
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| madebyaris/poinf-of-sales.cursor/rules/admin-interface-patterns.mdc · 118 | Cursor rules | stylearchsecurityapi+2 | 62/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/api-patterns.mdc · 118 | Cursor rules | lint-formatstylesecuritydatabase+3 | 62/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/authentication-and-security-patterns.mdc · 118 | Cursor rules | setupteststylesecurity+4 | 81/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/backend-golang.mdc · 118 | Cursor rules | testlint-formatstylearch+5 | 69/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/database-patterns.mdc · 118 | Cursor rules | stylearchtypessecurity+2 | 62/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/development-workflow.mdc · 118 | Cursor rules | setupbuildteststyle+3 | 86/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/docker-deployment.mdc · 118 | Cursor rules | setupbuildteststyle+8 | 77/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/frontend-react.mdc · 118 | Cursor rules | buildtestlint-formatstyle+4 | 69/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/makefile-scripting.mdc · 118 | Cursor rules | setuplint-formatstylearch+2 | 81/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/performance-optimization-patterns.mdc · 118 | Cursor rules | buildteststyledatabase+3 | 66/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/project-architecture.mdc · 118 | Cursor rules | setupteststylearch+6 | 78/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/react-native-mobile-patterns.mdc · 118 | Cursor rules | buildstylearchui+2 | 74/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/role-based-access-patterns.mdc · 118 | Cursor rules | styletypessecuritydatabase+2 | 58/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/tech-debt-prevention.mdc · 118 | Cursor rules | styletesting-strategyui | 50/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/testing-patterns.mdc · 118 | Cursor rules | setupteststylearch+4 | 74/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/user-journey-optimization.mdc · 118 | Cursor rules | styleperformanceagent-behaviour | 50/100 | 3 days ago |
Diff against .cursor/rules/admin-interface-patterns.mdc Diff against .cursor/rules/api-patterns.mdc Diff against .cursor/rules/authentication-and-security-patterns.mdc Diff against .cursor/rules/backend-golang.mdc Diff against .cursor/rules/database-patterns.mdc Diff against .cursor/rules/development-workflow.mdc Diff against .cursor/rules/docker-deployment.mdc Diff against .cursor/rules/frontend-react.mdc Diff against .cursor/rules/makefile-scripting.mdc Diff against .cursor/rules/performance-optimization-patterns.mdc Diff against .cursor/rules/project-architecture.mdc Diff against .cursor/rules/react-native-mobile-patterns.mdc Diff against .cursor/rules/role-based-access-patterns.mdc Diff against .cursor/rules/tech-debt-prevention.mdc Diff against .cursor/rules/testing-patterns.mdc Diff against .cursor/rules/user-journey-optimization.mdc
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| hiromaily/go-crypto-wallet.cursor/rules/typescript.mdc · 126 | Cursor rules | setupbuildtestlint-format+6 | 100/100 | 3 days ago | |
| TechSquidTV/Hermes.cursor/rules/10-hermes-api.mdc · 45 | Cursor rules | testlint-formatstylearch+5 | 100/100 | 3 days ago | |
| markstev/mark-starter.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+6 | 99/100 | 3 days ago | |
| Allymahmoud/case-intake-platform.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| dodgecfr/combatfilms-webapp.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| deifos/clipmira-subtitles.cursor/rules/frontend.mdc · 1 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| langflow-ai/langflow.cursor/rules/docs_development.mdc · 153k | Cursor rules | setupbuildtestlint-format+7 | 97/100 | 3 days ago | |
| TechSquidTV/Hermes.cursor/rules/20-hermes-api-tests.mdc · 45 | Cursor rules | teststyletesting-strategysecurity+3 | 97/100 | 3 days ago |
