|
| 1 | +/** |
| 2 | + * Real-time Stock Updates Composable |
| 3 | + * |
| 4 | + * Listens to Socket.IO events for stock changes and notifies registered handlers. |
| 5 | + * Provides intelligent event management with deduplication and batching. |
| 6 | + * Each handler is responsible for filtering by warehouse and updating its cache. |
| 7 | + */ |
| 8 | + |
| 9 | +import { ref, onUnmounted } from 'vue' |
| 10 | + |
| 11 | +// Shared state across all instances |
| 12 | +const isListening = ref(false) |
| 13 | +const eventHandlers = new Set() |
| 14 | +const pendingUpdates = new Map() |
| 15 | +let batchTimeout = null |
| 16 | + |
| 17 | +/** |
| 18 | + * Batch update configuration |
| 19 | + */ |
| 20 | +const BATCH_DELAY_MS = 500 // Wait 500ms before applying batched updates |
| 21 | +const MAX_BATCH_SIZE = 100 // Maximum items to batch before forcing update |
| 22 | + |
| 23 | +/** |
| 24 | + * Process pending stock updates in batch |
| 25 | + */ |
| 26 | +async function processBatchedUpdates() { |
| 27 | + if (pendingUpdates.size === 0) { |
| 28 | + return |
| 29 | + } |
| 30 | + |
| 31 | + const updates = Array.from(pendingUpdates.values()) |
| 32 | + pendingUpdates.clear() |
| 33 | + |
| 34 | + try { |
| 35 | + // Notify all registered handlers |
| 36 | + // Each handler can filter by warehouse before applying updates |
| 37 | + eventHandlers.forEach(handler => { |
| 38 | + try { |
| 39 | + handler(updates) |
| 40 | + } catch (error) { |
| 41 | + console.error('[Realtime Stock] Handler error:', error) |
| 42 | + } |
| 43 | + }) |
| 44 | + } catch (error) { |
| 45 | + console.error('[Realtime Stock] Failed to process batch updates:', error) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Schedule batch processing |
| 51 | + */ |
| 52 | +function scheduleBatchUpdate() { |
| 53 | + if (batchTimeout) { |
| 54 | + clearTimeout(batchTimeout) |
| 55 | + } |
| 56 | + |
| 57 | + // Force update if batch is getting too large |
| 58 | + if (pendingUpdates.size >= MAX_BATCH_SIZE) { |
| 59 | + processBatchedUpdates() |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + batchTimeout = setTimeout(() => { |
| 64 | + processBatchedUpdates() |
| 65 | + batchTimeout = null |
| 66 | + }, BATCH_DELAY_MS) |
| 67 | +} |
| 68 | + |
| 69 | +/** |
| 70 | + * Handle incoming stock update event |
| 71 | + */ |
| 72 | +function handleStockUpdate(data) { |
| 73 | + if (!data || !data.stock_updates) { |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + // Add updates to pending batch (deduplicate by item_code + warehouse) |
| 78 | + data.stock_updates.forEach(update => { |
| 79 | + const key = `${update.item_code}|${update.warehouse}` |
| 80 | + pendingUpdates.set(key, update) |
| 81 | + }) |
| 82 | + |
| 83 | + scheduleBatchUpdate() |
| 84 | +} |
| 85 | + |
| 86 | +/** |
| 87 | + * Handle invoice created event (optional, for future use) |
| 88 | + */ |
| 89 | +function handleInvoiceCreated(data) { |
| 90 | + // Can be used to update sales dashboards, notifications, etc. |
| 91 | +} |
| 92 | + |
| 93 | +/** |
| 94 | + * Start listening to real-time events |
| 95 | + */ |
| 96 | +function startListening() { |
| 97 | + if (isListening.value) { |
| 98 | + return |
| 99 | + } |
| 100 | + |
| 101 | + if (!window.frappe?.realtime) { |
| 102 | + console.warn('[Realtime Stock] Socket.IO not available') |
| 103 | + return |
| 104 | + } |
| 105 | + |
| 106 | + // Subscribe to stock update events |
| 107 | + window.frappe.realtime.on('pos_stock_update', handleStockUpdate) |
| 108 | + window.frappe.realtime.on('pos_invoice_created', handleInvoiceCreated) |
| 109 | + |
| 110 | + isListening.value = true |
| 111 | +} |
| 112 | + |
| 113 | +/** |
| 114 | + * Stop listening to real-time events |
| 115 | + */ |
| 116 | +function stopListening() { |
| 117 | + if (!isListening.value) { |
| 118 | + return |
| 119 | + } |
| 120 | + |
| 121 | + if (window.frappe?.realtime) { |
| 122 | + window.frappe.realtime.off('pos_stock_update', handleStockUpdate) |
| 123 | + window.frappe.realtime.off('pos_invoice_created', handleInvoiceCreated) |
| 124 | + } |
| 125 | + |
| 126 | + // Clear pending updates |
| 127 | + if (batchTimeout) { |
| 128 | + clearTimeout(batchTimeout) |
| 129 | + batchTimeout = null |
| 130 | + } |
| 131 | + pendingUpdates.clear() |
| 132 | + |
| 133 | + isListening.value = false |
| 134 | +} |
| 135 | + |
| 136 | +/** |
| 137 | + * Flush pending updates immediately |
| 138 | + */ |
| 139 | +async function flushUpdates() { |
| 140 | + if (batchTimeout) { |
| 141 | + clearTimeout(batchTimeout) |
| 142 | + batchTimeout = null |
| 143 | + } |
| 144 | + await processBatchedUpdates() |
| 145 | +} |
| 146 | + |
| 147 | +/** |
| 148 | + * Main composable |
| 149 | + */ |
| 150 | +export function useRealtimeStock() { |
| 151 | + /** |
| 152 | + * Register a callback to be notified of stock updates |
| 153 | + * @param {Function} handler - Called with array of stock updates |
| 154 | + * @returns {Function} Cleanup function to unregister handler |
| 155 | + */ |
| 156 | + function onStockUpdate(handler) { |
| 157 | + if (typeof handler !== 'function') { |
| 158 | + throw new Error('Handler must be a function') |
| 159 | + } |
| 160 | + |
| 161 | + eventHandlers.add(handler) |
| 162 | + |
| 163 | + // Start listening when first handler is registered |
| 164 | + if (eventHandlers.size === 1) { |
| 165 | + startListening() |
| 166 | + } |
| 167 | + |
| 168 | + // Return cleanup function |
| 169 | + return () => { |
| 170 | + eventHandlers.delete(handler) |
| 171 | + |
| 172 | + // Stop listening when last handler is removed |
| 173 | + if (eventHandlers.size === 0) { |
| 174 | + stopListening() |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + // Cleanup on component unmount |
| 180 | + onUnmounted(() => { |
| 181 | + // Note: We don't stop listening here because other components |
| 182 | + // might still be using it. Each handler cleans up individually. |
| 183 | + }) |
| 184 | + |
| 185 | + return { |
| 186 | + isListening, |
| 187 | + onStockUpdate, |
| 188 | + flushUpdates, |
| 189 | + startListening, |
| 190 | + stopListening |
| 191 | + } |
| 192 | +} |
0 commit comments