Skip to content

Commit 3d202d3

Browse files
committed
Centralize historical lot 360 context
1 parent 092109b commit 3d202d3

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

‎src/components/Lot360Context.tsx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import {createContext,useContext,useEffect,useMemo,useState,type ReactNode} from 'react'
2+
import {HistoricalLotDrawer,type HistoricalRecord} from './HistoricalLotDrawer'
3+
4+
export type HistorySummary={total:string|number;operational:string|number;voids:string|number;flagged?:string|number;guide_kg:string|number|null;received_kg:string|number|null;first_event_date:string|null;last_event_date:string|null}
5+
type HistoryPayload={records?:HistoricalRecord[];summary?:HistorySummary;error?:string}
6+
type Lot360ContextValue={records:HistoricalRecord[];summary:HistorySummary|null;loading:boolean;error:string;openRecord:(record:HistoricalRecord)=>void;openBySourceRow:(sourceRow:number)=>void;close:()=>void}
7+
const Lot360Context=createContext<Lot360ContextValue|null>(null)
8+
9+
async function fetchHistory(){const response=await fetch('/api/history'),payload=await response.json() as HistoryPayload;if(!response.ok)throw new Error(payload.error??'No fue posible cargar la historia');return payload}
10+
11+
export function Lot360Provider({children}:{children:ReactNode}){
12+
const [records,setRecords]=useState<HistoricalRecord[]>([])
13+
const [summary,setSummary]=useState<HistorySummary|null>(null)
14+
const [loading,setLoading]=useState(true)
15+
const [error,setError]=useState('')
16+
const [selected,setSelected]=useState<HistoricalRecord|null>(null)
17+
useEffect(()=>{let active=true;fetchHistory().then(payload=>{if(active){setRecords(payload.records??[]);setSummary(payload.summary??null)}}).catch(reason=>{if(active)setError(reason instanceof Error?reason.message:'No fue posible cargar la historia')}).finally(()=>{if(active)setLoading(false)});return()=>{active=false}},[])
18+
const bySourceRow=useMemo(()=>new Map(records.map(record=>[record.source_row,record])),[records])
19+
const value=useMemo<Lot360ContextValue>(()=>({records,summary,loading,error,openRecord:setSelected,openBySourceRow:(sourceRow)=>{const record=bySourceRow.get(sourceRow);if(record)setSelected(record)},close:()=>setSelected(null)}),[records,summary,loading,error,bySourceRow])
20+
return <Lot360Context.Provider value={value}>{children}<HistoricalLotDrawer record={selected} onClose={()=>setSelected(null)}/></Lot360Context.Provider>
21+
}
22+
23+
export function useLot360(){const context=useContext(Lot360Context);if(!context)throw new Error('useLot360 debe usarse dentro de Lot360Provider');return context}

0 commit comments

Comments
 (0)