import {friendlyError,productLabel,resultLabel} from './userLanguage.mjs'; import React,{useEffect,useState,useRef} from 'react'; import {Users,Cloud,LogIn,LogOut,RefreshCw,ArchiveRestore,Archive,Send,ShieldCheck,ExternalLink,LoaderCircle} from 'lucide-react'; import {cloudConfigured,cloudClient,currentStaff,workspaceChanged} from './cloud.js'; import ReviewForm from './ReviewForm.jsx'; import CorrectiveActions from './CorrectiveActions.jsx'; import {parseReview,reviewBody} from './workflow.mjs'; import {startPolling} from './workspace.mjs'; import AccountSecurity from './AccountSecurity.jsx'; import {authWorkflowEnabled,privateTeamImages} from './authSecurity.mjs'; import {caseInterfaceEnabled,focusInspectionDetails} from './teamNavigation.mjs'; export default function TeamWorkspace({onOpenInspection,onOpenCorrectiveActions,onChooseInspection,casesView=false,initialInspectionId=null}){ const selection=useRef(0),selectionUser=useRef(null),loads=useRef(0),selectedRef=useRef(null),imageTime=useRef(0); const detailsRef=useRef(null),initialSelection=useRef(null); const [detailsOpened,setDetailsOpened]=useState(0),[opening,setOpening]=useState(false); const [sync,setSync]=useState({state:'refreshing'}); const [user,setUser]=useState(null),[staff,setStaff]=useState(null),[rows,setRows]=useState([]),[directory,setDirectory]=useState({}); const [email,setEmail]=useState(''),[password,setPassword]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[info,setInfo]=useState(''); const [archived,setArchived]=useState(false),[selected,setSelected]=useState(null),[images,setImages]=useState([]),[notes,setNotes]=useState([]),[note,setNote]=useState(''); const [recovery,setRecovery]=useState(false),[newPassword,setNewPassword]=useState(''),[confirm,setConfirm]=useState(false); const [securityClient,setSecurityClient]=useState(null); const authEnabled=authWorkflowEnabled(); const casesEnabled=caseInterfaceEnabled(window.DEFECTRAG_PUBLIC_CONFIG); useEffect(()=>()=>{images.filter(src=>src.startsWith('blob:')).forEach(src=>URL.revokeObjectURL(src))},[images]); useEffect(()=>{selectedRef.current=selected},[selected]); useEffect(()=>{if(selected)focusInspectionDetails(detailsRef.current)},[detailsOpened]); useEffect(()=>{ if(!user||!staff||!initialInspectionId)return; const key=user.id+':'+initialInspectionId; if(initialSelection.current===key)return; initialSelection.current=key;open({id:initialInspectionId},{focus:!casesView}); },[user?.id,staff?.user_id,initialInspectionId]); const configured=cloudConfigured(); // Approved Staff see their Team work first; account security moves below it. const security=authEnabled&&securityClient&&(!casesView||!staff)?{workspaceChanged();if(user)task(refresh)}}/>:null; async function task(action){setBusy(true);setError('');setInfo('');try{await action()}catch(e){setError(e.message||'Team request failed.')}finally{setBusy(false)}} async function refresh(){ const generation=++loads.current,selectionGeneration=selection.current,selectedID=selectedRef.current?.id; const {client,staff:member}=await currentStaff(); let query=client.from('shared_inspections').select('*').order('created_at',{ascending:false}).limit(200); query=archived?query.not('archived_at','is',null):query.is('archived_at',null); const [{data,error:queryError},{data:people,error:peopleError},noteResult]=await Promise.all([query,client.from('staff_members').select('*'),selectedID?client.from('staff_notes').select('*').eq('inspection_id',selectedID).order('created_at'):{data:[]}]); if(queryError)throw queryError;if(peopleError)throw peopleError;if(noteResult.error)throw noteResult.error; if(generation!==loads.current)return; setStaff(member);setError('');setRows(data||[]);setDirectory(Object.fromEntries((people||[]).map(p=>[p.user_id,p.display_name]))); if(selectedID&&selectionGeneration===selection.current){ const fresh=(data||[]).find(row=>row.id===selectedID); if(!fresh){selection.current++;setSelected(null);setImages([]);setNotes([])} else{ setSelected(fresh);setNotes(noteResult.data||[]); // Only signed links expire. Private blob copies stay valid while the page is open, // and re-downloading them made the photo reload on screen every few minutes. // Access is still re-checked by this refresh's own row queries above. if(!authEnabled&&Date.now()-imageTime.current>8*60*1000){ const urls=await Promise.all([fresh.image_path,fresh.heatmap_path].map(path=>client.storage.from('team-inspections').createSignedUrl(path,900))); if(generation===loads.current&&selectionGeneration===selection.current){if(urls.some(value=>value.error))throw new Error('Shared image links could not refresh.');setImages(urls.map(value=>value.data.signedUrl));imageTime.current=Date.now()} } } } } useEffect(()=>{if(!configured)return;let cancelled=false,subscription; cloudClient().then(async client=>{ if(!cancelled&&authEnabled)setSecurityClient(client); subscription=client.auth.onAuthStateChange((event,session)=>{if(!cancelled){const next=session?.user?.id||null;if(selectionUser.current!==next){selection.current++;loads.current++;setSelected(null);setRows([]);setImages([]);setNotes([]);setStaff(null);selectionUser.current=next}setUser(session?.user||null);if(event==='PASSWORD_RECOVERY')setRecovery(true)}}).data.subscription; const {data}=await client.auth.getUser();if(!cancelled)setUser(data.user); }).catch(e=>{if(!cancelled)setError(e.message)}); return()=>{cancelled=true;selection.current++;subscription?.unsubscribe()}; },[configured]); useEffect(()=>{if(!user)return;const poll=startPolling(refresh,{onState:value=>{setSync(value);if(value.error){setError(value.error);if(authEnabled){selection.current++;setRows([]);setDirectory({});setSelected(null);setImages([]);setNotes([]);setStaff(null)}}}}); return()=>{poll.stop();loads.current++}; },[user?.id,archived]); async function open(row,{focus=true}={}){ const generation=++selection.current; setOpening(true); try{await task(async()=>{ if(generation!==selection.current)return; const client=await cloudClient();const bucket=client.storage.from('team-inspections'); const [{data:fresh,error:recordError},{data,error}]=await Promise.all([ client.from('shared_inspections').select('*').eq('id',row.id).single(), client.from('staff_notes').select('*').eq('inspection_id',row.id).order('created_at')]); if(generation!==selection.current)return; if(recordError)throw recordError;if(error)throw error; const privateUrls=authEnabled?await privateTeamImages(client,fresh):null; const urls=privateUrls?privateUrls.map(src=>({data:{signedUrl:src}})):await Promise.all([fresh.image_path,fresh.heatmap_path].map(path=>bucket.createSignedUrl(path,900))); if(urls.some(r=>r.error))throw new Error('Private images could not be loaded. Check staff/storage policies.'); if(generation!==selection.current){privateUrls?.forEach(src=>URL.revokeObjectURL(src));return} selectedRef.current=fresh;imageTime.current=Date.now();setSelected(fresh);setImages(urls.map(r=>r.data.signedUrl));setNotes(data||[]);if(focus)setDetailsOpened(value=>value+1); })}finally{if(generation===selection.current)setOpening(false)} } function clearSelection(){selection.current++;selectedRef.current=null;setOpening(false);setSelected(null);setImages([]);setNotes([])} async function archiveMine(){await task(async()=>{ const client=await cloudClient();const ids=rows.filter(r=>r.owner_id===user.id).map(r=>r.id); if(ids.length){const {error}=await client.rpc('archive_team_inspections',{p_ids:ids});if(error)throw error;} selection.current++;setSelected(null);setConfirm(false);await refresh();workspaceChanged(); })} if(!configured)return
TEAM WORKSPACE

Team workspace is not available yet.

The workspace administrator needs to connect shared storage before Staff can sign in here.

{[['01','Connect shared storage','The workspace administrator completes this setup.'],['02','Set up staff access','The administrator sets up approval and account security.'],['03','Connect this dashboard','The administrator connects the app, then Staff can sign in.']].map(([n,t,d])=>
{n}

{t}

{d}

)}
Administrator setup

Contact the workspace administrator for help. The public demo can be used without Staff access.

; return <>

{casesView?'Corrective Actions access':'Staff workspace'}

{staff?'Inspections your team has shared. New inspections stay private until you share them.':'Sign in to review inspections your team has shared.'}

STAFF ACCESS
{error&&
{friendlyError(error)}
} {info&&
{info}
} {opening&&

Opening the shared photo and review…

} {casesView&&!casesEnabled&&

Corrective Actions has been turned off for this app. Inspections and reviews are still available. Contact the workspace administrator if needed.

} {user&&!staff&&security} {!user?<>

Sign in

{e.preventDefault();task(async()=>{const client=await cloudClient();const {error}=await client.auth.signInWithPassword({email,password});if(error)throw error;setPassword('')})}}>

{authEnabled?'A new account needs Developer approval before Staff work is available. Approved Staff must also enter their security code when asked.':'The workspace administrator must approve an account before it can access Staff work.'}

{security}:<>
{staff?.display_name||user.email}{staff?.role||'CHECKING ACCESS'}
{!casesView&&staff&&casesEnabled&&}{casesView&&staff&&}
{recovery&&
{e.preventDefault();task(async()=>{const client=await cloudClient();const {error}=await client.auth.updateUser({password:newPassword});if(error)throw error;setNewPassword('');setRecovery(false)})}}>
} {!casesView&&<>
{rows.length} shared inspections · {sync.state==='synced'?'updated '+new Date(sync.at).toLocaleTimeString([],{hour:'numeric',minute:'2-digit'}):sync.state==='offline'?'offline; shown results may be out of date':sync.state==='stale'?'update failed; shown results may be out of date':'refreshing…'}{staff?.role==='developer'&&}{!archived&&}
{confirm&&
Archive your visible records?

They will leave the shared active history. Original files and conversations remain recoverable by a developer. Other staff members’ records will stay active.

}
{rows.map(row=>)}
InspectionProductResultShared bySaved
{row.id.slice(0,8)}{productLabel(row.payload.category)}{resultLabel(row.payload.verdict)}{directory[row.owner_id]||'Staff member'}{new Date(row.created_at).toLocaleString()}{archived&&staff?.role==='developer'&&}
{!rows.length&&

{archived?'No archived records to recover.':'No shared inspections yet. Open an inspection result and select Share with team.'}

}
} } {user&&staff&&security&&
Account & security{security}
}
{casesView&&user&&staff&&casesEnabled&&id?open({id},{focus:false}):clearSelection()} onEvidence={id=>open({id})}/>} {user&&selected&&

Shared inspection · {selected.id.slice(0,8)}

Shared by {directory[selected.owner_id]||'a colleague'}. These are saved results. Nothing is checked again.

{onOpenInspection&&!selected.archived_at&&}{!casesView&&casesEnabled&&!selected.archived_at&&}
{images.map((src,i)=>{i?'Saved)}
SAVED RESULT{resultLabel(selected.payload.verdict)} · score {Number(selected.payload.score).toFixed(5)} · review limit {Number(selected.payload.threshold).toFixed(5)}

Saved assistant conversation

{selected.conversation?.length?selected.conversation.map((m,i)=>

{m.role==='user'?'Inspector':'Evidence Assistant'}: {m.question||m.answer}

):

No assistant conversation was shared with this inspection.

}{!selected.archived_at&&parseReview(n,directory)).filter(Boolean).at(-1)} disabled={busy} onSave={async value=>{ const client=await cloudClient();const {error}=await client.from('staff_notes').insert({inspection_id:selected.id,author_id:user.id,body:reviewBody(value.status,value.decision,value.note)}); if(error)throw error;await open(selected,{focus:!casesView});workspaceChanged(); }}/>}

Team notes

{notes.filter(n=>!parseReview(n,directory)).map(n=>
{directory[n.author_id]||'Staff member'}

{n.body}

{new Date(n.created_at).toLocaleString()}
)}{!selected.archived_at&&
{e.preventDefault();task(async()=>{const client=await cloudClient();const {error}=await client.from('staff_notes').insert({inspection_id:selected.id,author_id:user.id,body:note.trim()});if(error)throw error;setNote('');await open(selected);workspaceChanged()})}}>setNote(e.target.value)}/>
}
}; }