RuleStack

Configs

Stacks

Compare

Diff

RuleStack

Configs

Stacks

Compare

Diff

Read API

RuleStack

Configs

Stacks

Compare

Diff

Read API

Configs/Cursor rules/madebyaris/poinf-of-sales

Cursor rule

.cursor/rules/business-logic-patterns.mdc

Comprehensive 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 blocks

Repository

118

— · pushed 339 days ago

Last changed

3 days ago

First indexed 3 days ago.
madebyaris/poinf-of-sales/.cursor/rules/business-logic-patterns.mdcRawGitHub
1---
2description: Comprehensive business logic patterns for POS System domain understanding, user journeys, and workflow optimization
3---
4 
5# 🍽️ POS Business Logic & Domain Patterns
6 
7## 🎯 Core Business Domain Understanding
8 
9### Restaurant Operations Model
10The POS system orchestrates complex restaurant operations with multiple stakeholders and intricate workflows:
11 
12```typescript
13// Domain Model - Core Business Entities
14interface RestaurantDomain {
15 // Revenue Generation
16 orders: OrderLifecycle[]
17 payments: PaymentProcessing[]
18 inventory: InventoryManagement
19
20 // Operations Management
21 tables: TableManagement
22 staff: StaffOperations
23 kitchen: KitchenWorkflow
24
25 // Business Intelligence
26 analytics: BusinessAnalytics
27 reporting: FinancialReporting
28}
29 
30// Business Rules Engine
31class POSBusinessRules {
32 validateOrderCreation(order: CreateOrderRequest): ValidationResult
33 calculatePricing(items: OrderItem[]): PricingCalculation
34 manageInventory(productId: string, quantity: number): InventoryResult
35 optimizeKitchenWorkflow(orders: Order[]): WorkflowOptimization
36}
37```
38 
39## 🔄 Critical User Journeys & Performance Optimization
40 
41### 1. Server Journey: Dine-In Order Creation (Target: <30 seconds)
42```typescript
43// ✅ PERFORMANCE-OPTIMIZED: Server workflow
44class ServerWorkflowOptimization {
45 // Pre-load critical data for instant access
46 private async preloadServerData(): Promise<ServerContext> {
47 const [products, categories, tables, activeOrders] = await Promise.all([
48 this.productService.getAvailableProducts(), // Cache for 5 minutes
49 this.categoryService.getActiveCategories(), // Cache for 1 hour
50 this.tableService.getTableStatus(), // Real-time, 30s cache
51 this.orderService.getActiveOrders() // Real-time, 10s cache
52 ])
53
54 return { products, categories, tables, activeOrders }
55 }
56 
57 // Optimistic order creation with rollback
58 async createOrderOptimistic(orderData: CreateOrderRequest): Promise<Order> {
59 // 1. Immediate UI feedback (0ms)
60 this.ui.showOrderCreating(orderData)
61
62 // 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 }
67
68 // 3. Optimistic update (10-15ms)
69 const optimisticOrder = this.generateOptimisticOrder(orderData)
70 this.ui.showOrderCreated(optimisticOrder)
71
72 // 4. Background server sync (100-200ms)
73 try {
74 const serverOrder = await this.orderService.createOrder(orderData)
75 this.reconcileOptimisticOrder(optimisticOrder, serverOrder)
76 return serverOrder
77 } catch (error) {
78 // Rollback optimistic changes
79 this.rollbackOptimisticOrder(optimisticOrder)
80 throw error
81 }
82 }
83 
84 // Business rule validation (prevent API round-trips)
85 private async validateOrderBusiness(order: CreateOrderRequest): Promise<ValidationResult> {
86 const errors: string[] = []
87
88 // Table availability check
89 if (order.table_id && !this.isTableAvailable(order.table_id)) {
90 errors.push('Table is not available')
91 }
92
93 // Product availability batch check
94 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 }
100
101 // Business hours validation
102 if (!this.isDuringBusinessHours()) {
103 errors.push('Orders cannot be created outside business hours')
104 }
105
106 return { isValid: errors.length === 0, errors }
107 }
108}
109```
110 
111### 2. Enhanced Kitchen Journey: As-Ready Service Workflow (Target: <3 seconds per item update)
112```typescript
113// ✅ REAL-TIME OPTIMIZED: Enhanced kitchen workflow with individual item tracking
114class EnhancedKitchenWorkflowEngine {
115 private orderPriorityQueue: PriorityQueue<KitchenOrder>
116 private preparationTimers: Map<string, Timer>
117 private realTimeUpdates: EventEmitter
118 private soundNotificationSystem: SoundNotificationSystem
119 
120 // Intelligent order prioritization with as-ready service
121 async optimizeKitchenQueue(): Promise<KitchenOrder[]> {
122 const activeOrders = await this.getActiveKitchenOrders()
123
124 // Business logic: Priority calculation with individual item tracking
125 return activeOrders
126 .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 tracking
132 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 items
137 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 - aScore
140 })
141 }
142 
143 // As-ready service: Individual item completion
144 async markItemReady(orderId: string, itemId: string): Promise<void> {
145 await this.updateItemStatus(orderId, itemId, 'ready')
146 this.soundNotificationSystem.playItemReadySound() // 1200Hz beep
147 this.notifyCounterStaff(orderId, itemId)
148 }
149 
150 // As-ready service: Individual item serving
151 async serveReadyItem(orderId: string, itemId: string): Promise<void> {
152 await this.updateItemStatus(orderId, itemId, 'served')
153 this.soundNotificationSystem.playItemServedSound() // 1400Hz beep
154
155 // Check if entire order is complete
156 const order = await this.getOrder(orderId)
157 if (this.isOrderFullyServed(order)) {
158 await this.completeOrder(orderId)
159 this.removeFromKitchenDisplay(orderId)
160 }
161 }
162 
163 // Real-time status updates with business impact
164 async updateOrderStatus(orderId: string, status: KitchenStatus): Promise<void> {
165 const order = await this.getOrder(orderId)
166 const businessImpact = await this.calculateBusinessImpact(order, status)
167
168 // Update with business context
169 await this.orderService.updateOrderStatus(orderId, {
170 status,
171 estimated_completion: businessImpact.estimatedCompletion,
172 kitchen_notes: businessImpact.notes,
173 affects_other_orders: businessImpact.dependencies
174 })
175
176 // Trigger real-time notifications
177 this.notifyStakeholders(order, status, businessImpact)
178
179 // Update kitchen display optimization
180 this.reoptimizeKitchenQueue()
181 }
182 
183 // Business intelligence: Kitchen performance metrics
184 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```
195 
196### 3. Counter Journey: Payment Processing (Target: <10 seconds)
197```typescript
198// ✅ PAYMENT-OPTIMIZED: Multi-step payment with error handling
199class PaymentWorkflowEngine {
200 // Payment processing with comprehensive business validation
201 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 }
207
208 // 2. Calculate final amounts with business rules
209 const calculation = await this.calculatePaymentAmounts(paymentRequest)
210
211 // 3. Process payment with error handling
212 try {
213 const result = await this.executePayment(calculation)
214
215 // 4. Update business state
216 await this.updateBusinessState(result)
217
218 // 5. Generate receipt and analytics
219 await this.generateReceiptAndAnalytics(result)
220
221 return result
222 } catch (error) {
223 await this.handlePaymentError(error, paymentRequest)
224 throw error
225 }
226 }
227 
228 // Business-aware payment validation
229 private async validatePaymentBusiness(request: PaymentRequest): Promise<ValidationResult> {
230 const order = await this.orderService.getOrder(request.order_id)
231 const errors: string[] = []
232
233 // Order state validation
234 if (!['ready', 'served'].includes(order.status)) {
235 errors.push('Order must be ready or served before payment')
236 }
237
238 // Amount validation with business rules
239 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 }
243
244 // Business hours and policies
245 if (request.payment_method === 'check' && !this.acceptsChecks()) {
246 errors.push('Check payments not accepted during this period')
247 }
248
249 // Tip validation for business rules
250 if (request.tip_amount && request.tip_amount > expectedTotal * 0.3) {
251 errors.push('Tip amount seems unusually high, please confirm')
252 }
253
254 return { isValid: errors.length === 0, errors }
255 }
256 
257 // Advanced payment calculation with business intelligence
258 private async calculatePaymentAmounts(request: PaymentRequest): Promise<PaymentCalculation> {
259 const order = await this.orderService.getOrderWithItems(request.order_id)
260
261 return {
262 subtotal: this.calculateSubtotal(order.items),
263 tax: this.calculateTax(order.items), // Business-specific tax rules
264 discounts: await this.calculateDiscounts(order), // Loyalty, promotions
265 serviceCharge: this.calculateServiceCharge(order), // Table service, large parties
266 tip: request.tip_amount || 0,
267 finalTotal: this.calculateFinalTotal(order, request),
268 paymentBreakdown: this.generatePaymentBreakdown(request)
269 }
270 }
271}
272```
273 
274## 🏗️ Tech Debt Prevention Patterns
275 
276### 1. Consistency Enforcement
277```typescript
278// ✅ CONSISTENT: Standardized patterns across the system
279namespace POSConsistency {
280 // API Response consistency
281 export interface StandardAPIResponse<T> {
282 success: boolean
283 message: string
284 data?: T
285 error?: string
286 timestamp: string
287 request_id: string // For debugging and tracing
288 }
289 
290 // Error handling consistency
291 export class BusinessError extends Error {
292 code: string
293 userMessage: string
294 context: Record<string, any>
295
296 constructor(code: string, message: string, userMessage: string, context?: Record<string, any>) {
297 super(message)
298 this.code = code
299 this.userMessage = userMessage
300 this.context = context || {}
301 }
302 }
303 
304 // State management consistency
305 export interface BaseEntityState<T> {
306 items: T[]
307 loading: boolean
308 error: string | null
309 lastUpdated: Date
310 optimisticUpdates: Map<string, T>
311 }
312}
313```
314 
315### 2. DRY Principle Enforcement
316```typescript
317// ✅ DRY: Reusable business logic components
318class ReusableBusinessComponents {
319 // Unified validation system
320 static createValidator<T>(schema: ValidationSchema<T>) {
321 return {
322 validate: (data: T): ValidationResult => {
323 const errors: string[] = []
324
325 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 })
333
334 return { isValid: errors.length === 0, errors }
335 }
336 }
337 }
338 
339 // Unified caching system
340 static createCacheManager<T>(config: CacheConfig) {
341 const cache = new Map<string, CacheEntry<T>>()
342
343 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.data
348 }
349
350 const data = await fetcher()
351 cache.set(key, {
352 data,
353 expiresAt: Date.now() + config.ttl,
354 createdAt: Date.now()
355 })
356
357 return data
358 },
359
360 invalidate: (key: string) => cache.delete(key),
361 clear: () => cache.clear()
362 }
363 }
364 
365 // Unified state management
366 static createStateManager<T>(initialState: T) {
367 const subscribers = new Set<(state: T) => void>()
368 let currentState = { ...initialState }
369
370 return {
371 getState: () => currentState,
372 setState: (updater: (state: T) => T) => {
373 const newState = updater(currentState)
374 currentState = newState
375 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```
385 
386## ⚡ Performance-First Development Patterns
387 
388### 1. Database Performance Optimization
389```go
390// ✅ PERFORMANCE: Intelligent query optimization with business understanding
391type QueryOptimizer struct {
392 db *sql.DB
393 queryCache *QueryCache
394 performanceMetrics *PerformanceMetrics
395}
396 
397// Business-aware query optimization
398func (q *QueryOptimizer) GetOrdersOptimized(ctx context.Context, params OrderQueryParams) (*OrdersResult, error) {
399 // 1. Query planning based on business patterns
400 queryPlan := q.createQueryPlan(params)
401
402 // 2. Use business-specific indexes
403 query := `
404 SELECT
405 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 application
410 SUM(oi.quantity * oi.price) as calculated_total
411 FROM orders o
412 -- Performance: Use covering indexes
413 LEFT JOIN users u ON o.user_id = u.id
414 LEFT JOIN dining_tables t ON o.table_id = t.id
415 LEFT JOIN order_items oi ON o.id = oi.order_id
416 WHERE 1=1
417 `
418
419 args := []interface{}{}
420 argIndex := 1
421
422 // Business-aware filtering
423 if params.Status != "" {
424 query += fmt.Sprintf(" AND o.status = $%d", argIndex)
425 args = append(args, params.Status)
426 argIndex++
427 }
428
429 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 += 2
433 }
434
435 // Performance: Smart pagination with business context
436 if params.UserRole == "kitchen" {
437 // Kitchen sees only orders that need preparation
438 query += " AND o.status IN ('pending', 'confirmed', 'preparing')"
439 query += " ORDER BY o.priority DESC, o.created_at ASC" // Urgency first
440 } else {
441 query += " ORDER BY o.created_at DESC"
442 }
443
444 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)
447
448 // Execute with performance monitoring
449 start := time.Now()
450 rows, err := q.db.QueryContext(ctx, query, args...)
451 duration := time.Since(start)
452
453 // Business intelligence: Track query performance
454 q.performanceMetrics.RecordQuery("get_orders", duration, len(args))
455
456 if duration > 100*time.Millisecond {
457 log.Printf("SLOW QUERY WARNING: get_orders took %v", duration)
458 }
459
460 return q.processOrderResults(rows)
461}
462```
463 
464### 2. Frontend Performance with Business Intelligence
465```typescript
466// ✅ PERFORMANCE: Intelligent component optimization with business understanding
467class BusinessIntelligentComponents {
468 // Smart memoization based on business context
469 static createSmartMemo<T extends ComponentProps>(
470 Component: React.FC<T>,
471 businessContext: BusinessContext
472 ): React.FC<T> {
473 return React.memo(Component, (prevProps, nextProps) => {
474 // Business-aware comparison
475 if (businessContext.isHighFrequencyUpdate) {
476 // Kitchen orders update frequently - check only critical props
477 return (
478 prevProps.id === nextProps.id &&
479 prevProps.status === nextProps.status &&
480 prevProps.priority === nextProps.priority
481 )
482 } else {
483 // Admin data changes less frequently - deep comparison ok
484 return isEqual(prevProps, nextProps)
485 }
486 })
487 }
488 
489 // Intelligent data prefetching based on user journey
490 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 data
496 },
497 server: {
498 prefetchOnIdle: ['menu-items', 'table-status'],
499 preloadCritical: ['available-tables', 'active-categories'],
500 cacheStrategy: 'moderate' // Balance speed vs memory
501 },
502 kitchen: {
503 prefetchOnIdle: [],
504 preloadCritical: ['pending-orders', 'preparation-queue'],
505 cacheStrategy: 'minimal' // Real-time data, minimal cache
506 }
507 }
508 
509 return prefetchStrategy[userRole]
510 }
511}
512```
513 
514## 🧪 QA Integration & Error Prevention
515 
516### 1. Business Logic Testing Patterns
517```typescript
518// ✅ QA: Business logic testing with domain understanding
519describe('POS Business Logic Tests', () => {
520 describe('Order Creation Business Rules', () => {
521 it('should prevent order creation outside business hours', async () => {
522 // Given: Restaurant is closed
523 const mockTime = new Date('2024-01-01T02:00:00') // 2 AM
524 jest.setSystemTime(mockTime)
525
526 // When: Server attempts to create order
527 const orderRequest = createMockOrderRequest({
528 order_type: 'dine_in',
529 items: [{ product_id: 'burger-1', quantity: 1 }]
530 })
531
532 // Then: Should reject with business rule error
533 await expect(orderService.createOrder(orderRequest))
534 .rejects
535 .toThrow(BusinessRuleError)
536 .toMatchBusinessRule('OUTSIDE_BUSINESS_HOURS')
537 })
538 
539 it('should calculate complex pricing with discounts and tax', async () => {
540 // Given: Order with loyalty discount and special tax rules
541 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 ]
546
547 // When: Calculate final pricing
548 const pricing = await pricingService.calculateOrderTotal({
549 items: orderItems,
550 customer,
551 appliedPromotions: ['GOLD_10_PERCENT']
552 })
553
554 // Then: Should apply business rules correctly
555 expect(pricing).toMatchBusinessCalculation({
556 subtotal: 33.96,
557 discount: 3.40, // 10% gold discount
558 tax: 2.75, // 9% tax after discount
559 total: 33.31
560 })
561 })
562 })
563 
564 describe('Kitchen Workflow Business Rules', () => {
565 it('should prioritize orders based on business intelligence', async () => {
566 // Given: Multiple orders with different priorities
567 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 ]
572
573 // When: Kitchen optimizes queue
574 const optimizedQueue = await kitchenService.optimizeOrderQueue(orders)
575
576 // Then: Should prioritize based on business rules
577 expect(optimizedQueue).toMatchBusinessPriority([
578 'vip-1', // VIP table trumps wait time
579 'regular-2', // Shorter wait time + medium complexity
580 'regular-1' // Longest wait but easiest to complete
581 ])
582 })
583 })
584})
585 
586// Custom Jest matchers for business logic
587expect.extend({
588 toMatchBusinessRule(received: Error, expectedRule: string) {
589 const pass = received instanceof BusinessRuleError && received.code === expectedRule
590 return {
591 message: () => `Expected business rule ${expectedRule}, got ${received.constructor.name}`,
592 pass
593 }
594 },
595
596 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 calculations
600 })
601
602 return {
603 message: () => `Business calculation mismatch: expected ${JSON.stringify(expected)}, got ${JSON.stringify(received)}`,
604 pass: toleranceChecks
605 }
606 }
607})
608```
609 
610### 2. Error Prevention with Business Context
611```typescript
612// ✅ ERROR PREVENTION: Comprehensive error handling with business intelligence
613class BusinessErrorPrevention {
614 // Intelligent error recovery based on business impact
615 static createErrorRecoveryManager(businessContext: BusinessContext) {
616 return {
617 handleOrderError: async (error: Error, orderContext: OrderContext) => {
618 const businessImpact = this.assessBusinessImpact(error, orderContext)
619
620 switch (businessImpact.severity) {
621 case 'critical':
622 // Revenue-affecting errors - immediate escalation
623 await this.notifyManagement(error, orderContext)
624 await this.createEmergencyBackup()
625 return this.initiateFailsafeMode(orderContext)
626
627 case 'high':
628 // Customer-affecting errors - graceful degradation
629 await this.notifyStaff(error, orderContext)
630 return this.provideFallbackService(orderContext)
631
632 case 'medium':
633 // Performance errors - log and continue
634 this.logBusinessError(error, orderContext)
635 return this.retryWithBackoff(orderContext)
636
637 case 'low':
638 // Minor errors - silent recovery
639 return this.silentRecover(orderContext)
640 }
641 },
642
643 assessBusinessImpact: (error: Error, context: OrderContext): BusinessImpactAssessment => {
644 // Business intelligence for error severity
645 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 }
652
653 return this.computeBusinessSeverity(factors)
654 }
655 }
656 }
657 
658 // Proactive error prevention
659 static createPreventiveHealthChecks() {
660 return {
661 // Business-critical system health
662 checkOrderSystemHealth: async (): Promise<HealthCheck> => {
663 const checks = await Promise.all([
664 this.checkDatabasePerformance(), // Order creation speed
665 this.checkPaymentGateway(), // Payment processing
666 this.checkKitchenConnectivity(), // Kitchen display updates
667 this.checkInventorySync(), // Product availability
668 this.checkTableManagement() // Table status accuracy
669 ])
670
671 return this.aggregateHealthStatus(checks)
672 },
673
674 // Predictive failure detection
675 detectPotentialFailures: async (): Promise<PredictiveAlert[]> => {
676 const alerts: PredictiveAlert[] = []
677
678 // Database performance degradation
679 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 }
687
688 // Kitchen queue overload
689 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 }
698
699 return alerts
700 }
701 }
702 }
703}
704```
705 
706## 📊 Business Intelligence Integration
707 
708### 1. Performance Monitoring with Business Context
709```typescript
710// ✅ BUSINESS INTELLIGENCE: Performance monitoring with business insights
711class BusinessIntelligenceMonitoring {
712 // Revenue-aware performance tracking
713 static trackBusinessMetrics(operation: string, duration: number, businessContext: BusinessContext): void {
714 const metrics = {
715 operation,
716 duration,
717 timestamp: Date.now(),
718
719 // Business context
720 revenueImpact: businessContext.calculateRevenueImpact(duration),
721 customerImpact: businessContext.calculateCustomerImpact(duration),
722 operationalEfficiency: businessContext.calculateEfficiency(duration),
723
724 // Performance classification
725 performanceGrade: this.classifyPerformance(operation, duration),
726 businessCriticality: this.assessBusinessCriticality(operation, businessContext)
727 }
728
729 // Real-time business alerts
730 if (metrics.revenueImpact > 100) { // $100+ revenue at risk
731 this.sendBusinessAlert(`High revenue impact detected: ${operation} took ${duration}ms`)
732 }
733
734 // Performance optimization recommendations
735 if (metrics.performanceGrade === 'poor') {
736 this.generateOptimizationRecommendation(metrics)
737 }
738 }
739 
740 // Business-intelligent caching strategy
741 static createBusinessCache<T>() {
742 return {
743 // Cache strategy based on business value
744 set: (key: string, value: T, businessContext: BusinessContext) => {
745 const ttl = this.calculateOptimalTTL(key, businessContext)
746 const priority = this.calculateCachePriority(key, businessContext)
747
748 return this.cache.set(key, value, { ttl, priority })
749 },
750
751 // Intelligent cache invalidation
752 invalidateByBusinessEvent: (event: BusinessEvent) => {
753 const affectedKeys = this.getAffectedCacheKeys(event)
754 affectedKeys.forEach(key => this.cache.invalidate(key))
755 }
756 }
757 }
758}
759```
760 
761## 📱 Mobile Application Patterns (React Native)
762 
763### 1. Kitchen Staff Mobile App - Tablet & TV Display Optimization
764```typescript
765// ✅ MOBILE-OPTIMIZED: Kitchen display for tablets and large screens
766class MobileKitchenWorkflow {
767 // Touch-optimized interface patterns
768 private touchTargetSize = 50 // Minimum 50px for tablet touch
769 private gestureHandlers: GestureHandlerManager
770 private screenOrientation: 'landscape' | 'portrait'
771 
772 // Large screen TV display mode
773 async initializeTVDisplayMode(): Promise<void> {
774 this.screenOrientation = 'landscape'
775 this.enableAutoRotation(false)
776 this.setFullScreenMode(true)
777 this.optimizeForDistance(true) // Larger fonts, higher contrast
778
779 // TV-specific optimizations
780 await this.configureDisplaySettings({
781 fontSize: 'extra-large',
782 contrast: 'high',
783 colorScheme: 'high-visibility',
784 touchTargets: 'extra-large' // 60px+ for wall-mounted displays
785 })
786 }
787 
788 // Tablet-specific optimizations
789 async initializeTabletMode(): Promise<void> {
790 this.enableGestureNavigation()
791 this.optimizeForHandheld(true)
792
793 // Tablet-specific features
794 await this.configureTabletSettings({
795 swipeGestures: true,
796 pinchToZoom: false, // Prevent accidental zooming
797 hapticFeedback: true,
798 orientationLock: 'landscape-primary'
799 })
800 }
801 
802 // Offline mode for kitchen operations
803 async enableOfflineMode(): Promise<void> {
804 await this.syncCriticalData() // Orders, menu items, status updates
805 this.enableLocalStorage()
806 this.setupOfflineQueue() // Queue updates for when connection returns
807
808 // Offline-first architecture
809 this.dataManager.setPriority('local-first')
810 this.notificationManager.enableLocalNotifications()
811 }
812}
813```
814 
815### 2. Server Group Mobile App - Smartphone & Tablet Flexibility
816```typescript
817// ✅ MOBILE-OPTIMIZED: Server workflow for smartphones and tablets
818class MobileServerWorkflow {
819 private deviceType: 'smartphone' | 'tablet'
820 private paymentIntegration: MobilePaymentProcessor
821
822 // Adaptive UI based on device size
823 async initializeDeviceOptimization(): Promise<void> {
824 this.deviceType = await this.detectDeviceType()
825
826 if (this.deviceType === 'smartphone') {
827 await this.optimizeForSmartphone()
828 } else {
829 await this.optimizeForTablet()
830 }
831 }
832 
833 // Smartphone-specific optimizations
834 private async optimizeForSmartphone(): Promise<void> {
835 this.ui.setLayout('single-column')
836 this.ui.enableBottomNavigation()
837 this.ui.setTouchTargets('standard') // 44px minimum
838
839 // One-handed operation support
840 this.ui.enableReachabilityMode()
841 this.ui.setQuickActions(['add-item', 'view-cart', 'process-payment'])
842 }
843 
844 // Tablet-specific optimizations
845 private async optimizeForTablet(): Promise<void> {
846 this.ui.setLayout('multi-column')
847 this.ui.enableSideNavigation()
848 this.ui.setTouchTargets('large') // 50px for tablet use
849
850 // Multi-tasking support
851 this.ui.enableSplitView() // Menu + cart simultaneously
852 this.ui.setAdvancedGestures(true)
853 }
854 
855 // Mobile payment processing
856 async processMobilePayment(amount: number, method: PaymentMethod): Promise<PaymentResult> {
857 // Integration with mobile card readers
858 if (method === 'card') {
859 return await this.paymentIntegration.processCardPayment(amount)
860 }
861
862 // NFC/contactless payments
863 if (method === 'contactless') {
864 return await this.paymentIntegration.processNFCPayment(amount)
865 }
866
867 // Mobile wallet integration
868 if (method === 'mobile_wallet') {
869 return await this.paymentIntegration.processMobileWallet(amount)
870 }
871 }
872}
873```
874 
875### 3. Cross-Platform Synchronization Patterns
876```typescript
877// ✅ SYNC-OPTIMIZED: Real-time synchronization between web and mobile
878class CrossPlatformSyncManager {
879 private webSocketConnection: WebSocketManager
880 private offlineQueue: OfflineOperationQueue
881 private conflictResolver: DataConflictResolver
882 
883 // Real-time data synchronization
884 async initializeCrossPlatformSync(): Promise<void> {
885 // Establish WebSocket connection for real-time updates
886 await this.webSocketConnection.connect()
887
888 // Listen for cross-platform events
889 this.webSocketConnection.on('order-updated', this.handleOrderUpdate)
890 this.webSocketConnection.on('kitchen-status-changed', this.handleKitchenUpdate)
891 this.webSocketConnection.on('payment-processed', this.handlePaymentUpdate)
892
893 // Sync offline operations when connection restored
894 this.webSocketConnection.on('reconnected', this.syncOfflineOperations)
895 }
896 
897 // Handle data conflicts between platforms
898 async resolveDataConflicts(localData: any, serverData: any): Promise<any> {
899 // Business rules for conflict resolution
900 const resolution = await this.conflictResolver.resolve({
901 local: localData,
902 server: serverData,
903 strategy: 'server-wins-for-payments', // Critical business rule
904 fallback: 'merge-non-conflicting'
905 })
906
907 return resolution.resolvedData
908 }
909 
910 // Offline operation queuing
911 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```
921 
922## 🎯 Mobile Development Best Practices
923 
924### Performance Optimization for Mobile
925```typescript
926// Mobile-specific performance patterns
927class MobilePerformanceOptimizer {
928 // Battery-conscious background processing
929 async optimizeBatteryUsage(): Promise<void> {
930 // Reduce polling frequency when app is backgrounded
931 this.dataSync.setBackgroundPollingInterval(30000) // 30s instead of 5s
932
933 // Pause non-critical animations
934 this.ui.pauseDecoractiveAnimations()
935
936 // Optimize network requests
937 this.api.enableRequestBatching()
938 this.api.setConnectionPooling(true)
939 }
940 
941 // Memory management for long-running kitchen displays
942 async optimizeMemoryUsage(): Promise<void> {
943 // Limit order history in memory
944 this.orderManager.setMaxHistoryItems(50)
945
946 // Lazy load images and assets
947 this.assetManager.enableLazyLoading()
948
949 // Garbage collection optimization
950 this.schedulePeriodicCleanup(300000) // Every 5 minutes
951 }
952 
953 // Network optimization for mobile connections
954 async optimizeNetworkUsage(): Promise<void> {
955 // Compress API responses
956 this.api.enableCompression()
957
958 // Cache frequently accessed data
959 this.cache.setStrategy('aggressive-mobile')
960
961 // Implement smart retry logic
962 this.api.setRetryStrategy({
963 maxRetries: 3,
964 backoffMultiplier: 2,
965 networkAware: true // Adjust based on connection quality
966 })
967 }
968}
969```
970 
971This 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.
972 
973<function_calls>
974<invoke name="todo_write">
975<parameter name="merge">true

Commands it names

  • jest.setSystemTime(mockTime)

Sections

  • 🍽️ POS Business Logic & Domain Patterns
  • 🎯 Core Business Domain Understanding
  • Restaurant Operations Model
  • 🔄 Critical User Journeys & Performance Optimization
  • 1. Server Journey: Dine-In Order Creation (Target: <30 seconds)
  • 2. Enhanced Kitchen Journey: As-Ready Service Workflow (Target: <3 seconds per item update)
  • 3. Counter Journey: Payment Processing (Target: <10 seconds)
  • 🏗️ Tech Debt Prevention Patterns
  • 1. Consistency Enforcement
  • 2. DRY Principle Enforcement
  • ⚡ Performance-First Development Patterns
  • 1. Database Performance Optimization
  • 2. Frontend Performance with Business Intelligence
  • 🧪 QA Integration & Error Prevention
  • 1. Business Logic Testing Patterns
  • 2. Error Prevention with Business Context
  • 📊 Business Intelligence Integration
  • 1. Performance Monitoring with Business Context
  • 📱 Mobile Application Patterns (React Native)
  • 1. Kitchen Staff Mobile App - Tablet & TV Display Optimization
  • 2. Server Group Mobile App - Smartphone & Tablet Flexibility
  • 3. Cross-Platform Synchronization Patterns
  • 🎯 Mobile Development Best Practices
  • Performance Optimization for Mobile

What it covers

testcode-styledatabaseperformanceagent-behaviour

Stack — with the evidence

typescript

(1.00)

react

(1.00)

tailwind

(1.00)

docker

(1.00)

vite

(0.70)

eslint

(0.70)

javascript

(0.50)

Format

Cursor rules

The most expressive format here. Many small .mdc files, each with frontmatter declaring when it should load, so a rule about migrations only enters context when a migration is open. Costs the most to maintain and only one editor reads it.

What the corpus says about it

Repository

Owner
madebyaris
Language
—
License
—
Archived
no

All configs in this repo

Also in madebyaris/poinf-of-sales

Diff this repo’s formats

One 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?

The other instruction files in this repository
RepositoryFormatStackCoversScoreChanged
madebyaris/poinf-of-sales.cursor/rules/admin-interface-patterns.mdc · 118Cursor rulestypescriptreact+5stylearchsecurityapi+262/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/api-patterns.mdc · 118Cursor rulestypescriptreact+5lint-formatstylesecuritydatabase+362/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/authentication-and-security-patterns.mdc · 118Cursor rulestypescriptreact+5setupteststylesecurity+481/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/backend-golang.mdc · 118Cursor rulestypescriptreact+5testlint-formatstylearch+569/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/database-patterns.mdc · 118Cursor rulestypescriptreact+5stylearchtypessecurity+262/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/development-workflow.mdc · 118Cursor rulestypescriptreact+5setupbuildteststyle+386/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/docker-deployment.mdc · 118Cursor rulestypescriptreact+6setupbuildteststyle+877/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/frontend-react.mdc · 118Cursor rulestypescriptreact+5buildtestlint-formatstyle+469/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/makefile-scripting.mdc · 118Cursor rulestypescriptreact+5setuplint-formatstylearch+281/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/performance-optimization-patterns.mdc · 118Cursor rulestypescriptreact+5buildteststyledatabase+366/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/project-architecture.mdc · 118Cursor rulestypescriptreact+5setupteststylearch+678/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/react-native-mobile-patterns.mdc · 118Cursor rulestypescriptreact+5buildstylearchui+274/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/role-based-access-patterns.mdc · 118Cursor rulestypescriptreact+5styletypessecuritydatabase+258/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/tech-debt-prevention.mdc · 118Cursor rulestypescriptreact+5styletesting-strategyui50/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/testing-patterns.mdc · 118Cursor rulestypescriptreact+6setupteststylearch+474/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/user-journey-optimization.mdc · 118Cursor rulestypescriptreact+5styleperformanceagent-behaviour50/1003 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.

Same format, overlapping stack, ranked by quality
RepositoryFormatStackCoversScoreChanged
hiromaily/go-crypto-wallet.cursor/rules/typescript.mdc · 126Cursor rulesgobun+5setupbuildtestlint-format+6100/1003 days ago
TechSquidTV/Hermes.cursor/rules/10-hermes-api.mdc · 45Cursor rulestypescriptpytest+15testlint-formatstylearch+5100/1003 days ago
markstev/mark-starter.cursor/rules/frontend.mdc · 0Cursor rulestypescriptturborepo+14setuptestlint-formatstyle+699/1003 days ago
Allymahmoud/case-intake-platform.cursor/rules/frontend.mdc · 0Cursor rulestypescriptturborepo+13setuptestlint-formatstyle+799/1003 days ago
dodgecfr/combatfilms-webapp.cursor/rules/frontend.mdc · 0Cursor rulestypescriptturborepo+15setuptestlint-formatstyle+799/1003 days ago
deifos/clipmira-subtitles.cursor/rules/frontend.mdc · 1Cursor rulestypescriptnextjs+5setuptestlint-formatstyle+799/1003 days ago
langflow-ai/langflow.cursor/rules/docs_development.mdc · 153kCursor rulespythonnode+16setupbuildtestlint-format+797/1003 days ago
TechSquidTV/Hermes.cursor/rules/20-hermes-api-tests.mdc · 45Cursor rulestypescriptpytest+15teststyletesting-strategysecurity+397/1003 days ago
RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack