import {friendlyError,deliveryLabel,eventLabel,productLabel} from './userLanguage.mjs'; import React,{useEffect,useRef,useState} from 'react'; import {cloudClient,workspaceChanged} from './cloud.js'; import {caseCanEdit,caseCreationGate,caseDraftError,caseMetrics,caseRpc,inspectionCaseStatus,latestDefectReview,nextCaseStates} from './correctiveActions.mjs'; import {REVIEW_PREFIX} from './workflow.mjs'; import {startPolling} from './workspace.mjs'; import {focusInspectionDetails} from './teamNavigation.mjs'; import {DEFAULT_DUE_TIME,describeDue,dueParts,dueShortcuts,joinDue,localDate,shortcutDate,timeLabel,timeOptions} from './dueDate.mjs'; // Shortcuts plus a date-only calendar (closes on pick) and a time list replace the // browser's combined date-time popup, which has no clear way to confirm. // Server due dates are UTC; show them as the local value the picker uses. const when=iso=>new Date(iso).toLocaleString([],{dateStyle:'medium',timeStyle:'short'}); const localValue=iso=>{const d=new Date(iso);return localDate(d)+'T'+String(d.getHours()).padStart(2,'0')+':'+String(d.getMinutes()).padStart(2,'0')}; function dueField({legend,prefix,value,time,setValue,setTime,disabled,required,keep}){ const parts=dueParts(value),chosenTime=parts.time||time; const pickDate=date=>setValue(joinDue(date,chosenTime)); const pickTime=next=>{setTime(next);if(parts.date)setValue(joinDue(parts.date,next))}; return
{legend}
{keep&&} {dueShortcuts.map(s=>{const date=shortcutDate(s.days);return })}

{value?<>Due {describeDue(value)}:keep?keep:'Pick a day within the next year. Time starts at 5:00 PM.'}

; } export default function CorrectiveActions({user,inspection,notes=[],inspections=[],inspectionLoading=false,onSelectInspection,onEvidence}){ const generation=useRef(0),saving=useRef(false),previousInspection=useRef(inspection?.id); const caseDetails=useRef(null),casePanel=useRef(null),historyCase=useRef(null); const [access,setAccess]=useState('checking'); const [cases,setCases]=useState([]),[people,setPeople]=useState([]),[selected,setSelected]=useState(''); const [history,setHistory]=useState([]),[events,setEvents]=useState([]),[error,setError]=useState(''),[busy,setBusy]=useState(false); const [description,setDescription]=useState(''),[owner,setOwner]=useState(''),[supervisor,setSupervisor]=useState(''); const [priority,setPriority]=useState('Normal'),[due,setDue]=useState(''),[dueTime,setDueTime]=useState(DEFAULT_DUE_TIME),[confirmed,setConfirmed]=useState(false); const [state,setState]=useState(''),[note,setNote]=useState(''),[editVersion,setEditVersion]=useState(null); const [detailRefresh,setDetailRefresh]=useState(0),[editOwner,setEditOwner]=useState(''),[editSupervisor,setEditSupervisor]=useState(''),[editDue,setEditDue]=useState(''),[editDueTime,setEditDueTime]=useState(DEFAULT_DUE_TIME); const current=cases.find(c=>c.id===selected),review=latestDefectReview(notes),metrics=caseMetrics(cases); const creation=caseCreationGate(inspection,notes,cases,inspectionLoading); const draftError=caseDraftError({description,owner,supervisor,priority,due},people); const creationBlocked=!creation.ready?creation.reason:draftError||(!confirmed?'Tick the box to confirm the defect.':''); const [pickerNotes,setPickerNotes]=useState([]),[caseFilter,setCaseFilter]=useState('all'); const finished=c=>['Resolved','Closed','Cancelled'].includes(c.state),late=c=>!finished(c)&&Date.parse(c.due_at)true],['open','Open',c=>!finished(c)],['overdue','Overdue',late],['done','Done',finished]]; const shownCases=cases.filter(caseGroups.find(g=>g[0]===caseFilter)?.[2]||(()=>true)); const activeInspections=inspections.filter(row=>!row.archived_at); const activeIds=activeInspections.map(row=>row.id).join(','); // The selected inspection's notes prop is fresher right after a review is saved. const statusFor=row=>inspectionCaseStatus(row.id===inspection?.id?notes:pickerNotes.filter(n=>n.inspection_id===row.id),cases); const pickerRows=activeInspections.map(row=>({row,status:statusFor(row)})).sort((a,b)=>(b.status.key==='ready')-(a.status.key==='ready')); const readyCount=pickerRows.filter(item=>item.status.key==='ready').length; const canEdit=caseCanEdit(current,user.id,people.some(p=>p.user_id===user.id&&p.role==='developer')); const editConflict=!!current&&editVersion!==null&&editVersion!==current.version; async function load(){ const g=++generation.current,client=await cloudClient(); const permission=await client.rpc('defectrag_ca_staff'); if(g!==generation.current)return; if(permission.error||permission.data!==true){setAccess('denied');setCases([]);setPeople([]);setSelected('');setHistory([]);setEvents([]);throw new Error('Sign in with an approved Staff account and verify the security code before opening corrective actions.')} const results=await Promise.all([client.from('corrective_actions').select('*').order('created_at',{ascending:false}).limit(500), client.from('staff_members').select('user_id,display_name,role,revoked_at').is('revoked_at',null)]); if(g!==generation.current)return; if(results.some(r=>r.error)){setAccess('unavailable');setCases([]);setPeople([]);setSelected('');setHistory([]);setEvents([]);throw results.find(r=>r.error).error} setAccess('authorized');setCases(results[0].data||[]);setPeople(results[1].data||[]);setError('');setDetailRefresh(value=>value+1); } useEffect(()=>{const poll=startPolling(load,{onState:s=>{if(s.error){setAccess('unavailable');setError(s.error);setCases([]);setPeople([]);setSelected('');setHistory([]);setEvents([])}}}); return()=>{poll.stop();generation.current++}; },[user.id]); useEffect(()=>{const changed=()=>{generation.current++;setAccess('checking');setCases([]);setPeople([]);setSelected('');setHistory([]);setEvents([]);load().catch(e=>setError(e.message))};window.addEventListener('defectrag-auth-change',changed);return()=>window.removeEventListener('defectrag-auth-change',changed)},[user.id]); useEffect(()=>{ if(previousInspection.current&&previousInspection.current!==inspection?.id){setDescription('');setOwner('');setSupervisor('');setDue('');setPriority('Normal')} previousInspection.current=inspection?.id;setConfirmed(false); },[inspection?.id]); useEffect(()=>{setConfirmed(false)},[review?.id]); useEffect(()=>{let active=true;const ids=activeIds?activeIds.split(','):[]; if(access!=='authorized'||!ids.length){setPickerNotes([]);return} cloudClient().then(client=>client.from('staff_notes').select('id,inspection_id,author_id,body,created_at').in('inspection_id',ids).like('body',REVIEW_PREFIX+'%').order('created_at').limit(2000)) .then(({data,error})=>{if(!active)return;if(error)throw error;setPickerNotes(data||[])}) .catch(()=>{if(active)setPickerNotes([])}); return()=>{active=false}; },[access,activeIds,detailRefresh]); useEffect(()=>{if(access==='authorized')focusInspectionDetails(casePanel.current)},[access,inspection?.id,review?.id]); function resetCaseDraft(){setNote('');setState(current?.state||'');setEditOwner(current?.owner_id||'');setEditSupervisor(current?.supervisor_id||'');setEditDue('');setEditVersion(current?.version??null)} useEffect(resetCaseDraft,[current?.id]); useEffect(()=>{if(current)focusInspectionDetails(caseDetails.current)},[current?.id]); useEffect(()=>{let active=true;const issued=generation.current; if(!current||access!=='authorized'){historyCase.current=null;setHistory([]);setEvents([]);return} // Keep the shown history while polling refreshes the same case; clearing it on // every poll collapsed the panel and made the photo below jump in and out of view. if(historyCase.current!==current.id){historyCase.current=current.id;setHistory([]);setEvents([])} cloudClient().then(client=>Promise.all([ client.from('corrective_action_history').select('*').eq('case_id',current.id).order('version'), client.from('corrective_action_events').select('id,case_id,version,kind,status,attempts,last_error,created_at').eq('case_id',current.id).order('created_at',{ascending:false}) ])).then(values=>{if(!active||issued!==generation.current)return;if(values.some(r=>r.error))throw values.find(r=>r.error).error;setHistory(values[0].data||[]);setEvents(values[1].data||[])}).catch(e=>{if(active&&issued===generation.current)setError(e.message)}); return()=>{active=false}; },[current?.id,current?.version,detailRefresh,user.id,access]); async function task(action){if(saving.current)return;saving.current=true;setBusy(true);setError('');try{await action();await load();workspaceChanged()}catch(e){setError(e.message||'Corrective action request failed.')}finally{saving.current=false;setBusy(false)}} const name=id=>people.find(p=>p.user_id===id)?.display_name||'Former / unavailable staff'; return

Corrective Actions

Fix confirmed defects. Say who fixes each one, and by when.

{error&&
{friendlyError(error)}
} {access==='checking'&&

Checking your access…

} {access!=='checking'&&access!=='authorized'&&

Sign in on the Staff workspace page and enter your security code. Then come back here.

} {access==='authorized'&&<>
{metrics.open}Open
{metrics.overdue}Overdue
{metrics.resolved}Done
{metrics.averageResolutionHours===null?'–':metrics.averageResolutionHours.toFixed(1)+' h'}Average time to fix

Create a new case

    {['Pick an inspection','Save a defect review','Assign the fix'].map((label,i)=>{const at=!inspection?1:creation.ready||creation.existingCaseId?3:2;return
  1. {i+1{label}
  2. })}
{onSelectInspection&&} {onSelectInspection&&activeInspections.length>0&&

{readyCount?`${readyCount} inspection${readyCount>1?'s are':' is'} ready, listed first.`:'None are ready yet. A case needs a saved defect review.'}

} {onSelectInspection&&!activeInspections.length&&

No Team inspections yet. Open a personal inspection and choose “Share with team”.

}
{creation.ready?'Ready to assign':!inspection?'Step 1: pick an inspection':creation.existingCaseId?'This inspection already has a case':creation.needsReview?'Step 2: save a defect review':'Not available yet'}

{creation.reason}

{inspection&&!inspection.archived_at&&!inspectionLoading&&} {creation.existingCaseId&&}

You can fill this in now. Nothing is saved until you press “Create corrective action”.

{!people.length&&

No active Staff to assign. Press Refresh cases, or ask the administrator.

}
{e.preventDefault();if(creationBlocked||busy||saving.current)return;return task(async()=>{ const client=await cloudClient();const id=await caseRpc(client,'defectrag_create_corrective_action',{p_inspection:inspection.id,p_review:creation.review.id,p_confirmed:confirmed,p_owner:owner,p_supervisor:supervisor,p_priority:priority,p_description:description,p_due:new Date(due).toISOString()});setSelected(id);setDescription('');setConfirmed(false); })}}>