| | 1 | 1 | | import React, { createContext, useContext, useReducer } from 'react'; |
| | 1 | 2 | | |
| | 1 | 3 | | // Point 5: Reducer - Central decisions center |
| | 1 | 4 | | // Point 2: Structure - Status based instead of multiple booleans |
| | 1 | 5 | | const maintenanceReducer = (state, action) => { |
| | 11 | 6 | | switch (action.type) { |
| | 11 | 7 | | case 'UPDATE_STOCK': |
| | 0 | 8 | | return { ...state, stock: action.payload }; |
| | 11 | 9 | | case 'ADD_MACHINE': |
| | 2 | 10 | | return { ...state, machines: [...state.machines, action.payload] }; |
| | 11 | 11 | | case 'SET_MACHINES': |
| | 2 | 12 | | return { ...state, machines: action.payload }; |
| | 11 | 13 | | case 'SET_INVENTORY': |
| | 2 | 14 | | return { ...state, inventory: action.payload, stock: action.payload.reduce((acc, item) => acc + item.quantit |
| | 11 | 15 | | case 'SET_ALERTS': |
| | 2 | 16 | | return { ...state, alerts: action.payload }; |
| | 11 | 17 | | case 'SET_MAINTENANCE_LOGS': |
| | 2 | 18 | | return { ...state, maintenanceLogs: action.payload }; |
| | 11 | 19 | | case 'SET_STATUS': |
| | 0 | 20 | | return { ...state, appStatus: action.payload }; |
| | 11 | 21 | | case 'REMOVE_MACHINE': |
| | 1 | 22 | | return { ...state, machines: state.machines.filter(m => m.id !== action.payload) }; |
| | 11 | 23 | | default: |
| | 0 | 24 | | return state; |
| | 11 | 25 | | } |
| | 11 | 26 | | }; |
| | 1 | 27 | | |
| | 1 | 28 | | const initialState = { |
| | 1 | 29 | | stock: 0, |
| | 1 | 30 | | machines: [], |
| | 1 | 31 | | inventory: [], |
| | 1 | 32 | | alerts: [], |
| | 1 | 33 | | maintenanceLogs: [], |
| | 1 | 34 | | appStatus: 'idle' |
| | 1 | 35 | | }; |
| | 1 | 36 | | |
| | 1 | 37 | | // Point 6: Context - Data teleportation |
| | 1 | 38 | | const MaintenanceContext = createContext(null); |
| | 1 | 39 | | const MaintenanceDispatchContext = createContext(null); |
| | 1 | 40 | | |
| | 1 | 41 | | // Point 7: Scaling with Reducer + Context |
| | 1 | 42 | | export function MaintenanceProvider({ children }) { |
| | 24 | 43 | | const [state, dispatch] = useReducer(maintenanceReducer, initialState); |
| | 24 | 44 | | |
| | 24 | 45 | | return ( |
| | 24 | 46 | | <MaintenanceContext.Provider value={state}> |
| | 24 | 47 | | <MaintenanceDispatchContext.Provider value={dispatch}> |
| | 24 | 48 | | {children} |
| | 24 | 49 | | </MaintenanceDispatchContext.Provider> |
| | 24 | 50 | | </MaintenanceContext.Provider> |
| | 24 | 51 | | ); |
| | 24 | 52 | | } |
| | 1 | 53 | | |
| | 1 | 54 | | // Custom hooks for easier access |
| | 1 | 55 | | export function useMaintenance() { |
| | 112 | 56 | | return useContext(MaintenanceContext); |
| | 112 | 57 | | } |
| | 1 | 58 | | |
| | 1 | 59 | | export function useMaintenanceDispatch() { |
| | 47 | 60 | | return useContext(MaintenanceDispatchContext); |
| | 47 | 61 | | } |