Spaces:
Running

electrocheap / AnalysisPanel.jsx
kugguk's picture
Add CSV and JSON uploads for additional provider tariff histories
ee20ade verified
Raw History Blame Contribute Delete
14 kB
import React, {useState, useEffect} from 'react';
import {Upload, Download, RefreshCw, Play, Info, ArrowRight, CheckCircle2} from 'lucide-react';
import Papa from 'papaparse';
async function api(path,payload){const r=await fetch(path,{method:payload===undefined?'GET':'POST',headers:payload===undefined?{}:{'Content-Type':'application/json'},body:payload===undefined?undefined:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw Error(d.detail||'Request failed');return d;}
function save(value,name){const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=name;a.click();URL.revokeObjectURL(url);}
function SmallTable({rows,fields}){return <div className="table-wrap"><table><thead><tr>{fields.map(([key,label])=><th key={key}>{label}</th>)}</tr></thead><tbody>{rows.map((row,i)=><tr key={i}>{fields.map(([key])=><td key={key}>{typeof row[key]==='number'?row[key].toLocaleString(undefined,{maximumFractionDigits:3}):String(row[key]??'—')}</td>)}</tr>)}</tbody></table></div>}
function Note({children}){return <div className="notice"><Info size={17}/><div>{children}</div></div>}
export function AuditDatasets(){
const [catalog,setCatalog]=useState(null),[error,setError]=useState('');
useEffect(()=>{api('/api/datasets/manifest').then(setCatalog).catch(e=>setError(e.message));},[]);
return <section className="panel"><div className="section-title"><div><h2>Inspect the benchmark data</h2><p>Source snapshots, recorded predictions, truth values, protocol and checksums.</p></div><a className="secondary" href="/api/datasets/audit.zip" download><Download size={15}/>Public audit ZIP</a></div>{error&&<p role="alert">{error}</p>}<div className="dataset-list">{catalog?.datasets.map(d=><div className="dataset-row" key={d.dataset_id}><div><b>{d.title}</b><small>{d.rows.toLocaleString()} rows · {d.unit}</small><code>{d.sha256}</code></div><a className="text-button" href={d.download_path} download>CSV <Download size={13}/></a></div>)}</div><Note>These downloads contain official grid snapshots and recorded benchmark evidence. Uploaded customer bills and private analysis results are separate. Transformer/LLM evidence remains retrospective.</Note></section>;
}
export default function AnalysisPanel({country,quotes,onProfile,onError}){
const [busy,setBusy]=useState(false),[importJob,setImportJob]=useState(null),[imported,setImported]=useState(null),[job,setJob]=useState(null),[result,setResult]=useState(null),[reviewed,setReviewed]=useState(false),[future,setFuture]=useState(false),[growth,setGrowth]=useState(5),[history,setHistory]=useState(null),[mode,setMode]=useState('switching'),[bulkInput,setBulkInput]=useState(''),[selected,setSelected]=useState('');
const run=async(fn)=>{setBusy(true);onError('');try{await fn()}catch(e){onError(e.message)}finally{setBusy(false)}};
const poll=async(jid,type)=>{const r=await api('/api/analysis_result',{job_id:jid,limit:20});if(r.state==='failed')throw Error(r.error);if(type==='import'){setImportJob(r);if(r.state==='completed'){setImported(r.result);setReviewed(false);}}else{setJob(r);if(r.state==='completed')setResult(r.result);}return r;};
useEffect(()=>{let jid=importJob?.job_id;if(!jid||!['queued','running'].includes(importJob.state||'queued'))return;let id=setInterval(()=>poll(jid,'import').catch(e=>{onError(e.message);clearInterval(id);}),2500);return()=>clearInterval(id)},[importJob?.job_id,importJob?.state]);
useEffect(()=>{let jid=job?.job_id;if(!jid||!['queued','running'].includes(job.state||'queued'))return;let id=setInterval(()=>poll(jid,'analysis').catch(e=>{onError(e.message);clearInterval(id);}),2500);return()=>clearInterval(id)},[job?.job_id,job?.state]);
const upload=async(files)=>{if(!files.length)return;if([...files].reduce((s,f)=>s+f.size,0)>25*1024*1024)throw Error('Combined compressed files must be at most 25 MiB.');let form=new FormData();for(const f of files)form.append('files',f);const r=await fetch('/api/billing_import',{method:'POST',body:form});const data=await r.json();if(!r.ok)throw Error(data.detail||'Import failed');setImported(null);setImportJob({...data,state:'queued'});setSelected('');};
const profiles=imported?.profiles||[];
const submit=async()=>{let payload;if(mode==='switching'){const prices={};for(const q of quotes||[])prices[q.provider]=Number(growth);payload={kind:'switching',import_job_id:importJob?.job_id,profiles:selected?profiles.filter(p=>p.profile_id===selected):profiles,offers:quotes||[],horizons:[3,12,36],accept_profile_estimates:reviewed,assume_future_enrolment:future,price_scenarios:[{name:'constant-price',annual_price_change_pct:{}},{name:'declared-price-change',annual_price_change_pct:prices}]};}else{payload=JSON.parse(bulkInput);payload.kind=mode;}const data=await api('/api/analysis_submit',payload);setResult(null);setJob({...data,state:'queued'});};
const plans=result?.profiles?.flatMap(p=>p.plans.map(x=>({profile_id:p.profile_id,...x})))||[];
return <><div className="two-column"><section className="panel"><div className="section-title"><div><h2>Import compressed bills</h2><p>Keep multiple meters apart. Inspect what was extracted.</p></div><span className="source-pill">ZIP · PDF · CSV · JSON</span></div><label className="upload"><Upload size={22}/><b>Select billing archives or files</b><span>Up to 10 files · 25 MiB combined · 250 archive members</span><input aria-label="Upload compressed billing files" type="file" multiple accept=".zip,.pdf,.csv,.json" disabled={busy} onChange={e=>{const files=[...e.target.files];e.target.value='';run(()=>upload(files))}}/></label><Note>Text-based EDP Portugal PDFs are supported. Germany/Australia and other PDF layouts need normalized CSV/JSON. Water and unrelated files are excluded; scanned PDFs need OCR elsewhere. Raw files are used for this temporary computation and are not published.</Note>{importJob&&<div className="job-status"><span className="status-dot"/>Import: {importJob.state}<button className="text-button" onClick={()=>run(()=>poll(importJob.job_id,'import'))}><RefreshCw size={14}/>Refresh</button></div>}{imported&&<><SmallTable rows={Object.entries(imported.document_counts||{}).map(([status,count])=>({status,count}))} fields={[["status","Document outcome"],["count","Count"]]}/><div className="button-row"><a className="secondary" href={importJob.export_path} download><Download size={15}/>Private import audit</a><button className="secondary" onClick={()=>save(imported,'electrocheap-normalized-profile.json')}>Normalized JSON</button></div><label className="check-row"><input type="checkbox" checked={reviewed} onChange={e=>setReviewed(e.target.checked)}/><span>I reviewed the extracted consumption and electricity charges<small>PDF months are daily allocations; annual totals are estimates over covered days. Services, payment adjustments and water are excluded.</small></span></label></>}</section><section className="panel"><h2>Short, middle and long horizons</h2><p>Compare staying with constrained swap schedules over 3, 12 and 36 months, under explicit future-price assumptions.</p><div className="form-grid"><label className="field"><span>Analysis</span><select value={mode} onChange={e=>setMode(e.target.value)}><option value="switching">Provider swap scenarios</option><option value="forecast">Bulk live CPU forecasts</option><option value="benchmark">Bulk chronological benchmarks</option></select></label>{mode==='switching'&&<label className="field"><span>Profile</span><select value={selected} onChange={e=>setSelected(e.target.value)}><option value="">All imported profiles</option>{profiles.map(p=><option key={p.profile_id} value={p.profile_id}>{p.profile_id} · {p.contracted_power_kva??'?'} kVA</option>)}</select></label>}</div>{mode==='switching'?<><label className="field"><span>Declared annual price change · %</span><input type="number" value={growth} min="-90" max="300" onChange={e=>setGrowth(e.target.value)}/></label><label className="check-row"><input type="checkbox" checked={future} onChange={e=>setFuture(e.target.checked)}/><span>Assume supplied offers remain open for future swaps<small>This is a scenario, not a verified future offer. Default: enrol now; later entries need dated availability.</small></span></label><Note>{quotes?.length||0} supplied quotes loaded from Quote explorer. A comparison requires complete, fresh, tax-inclusive quotes matching each meter’s power and contract terms. Without quotes the scenario keeps the historical bill baseline.</Note></>:<><label className="field"><span>Normalized bulk request JSON</span><textarea rows={12} value={bulkInput} placeholder='{"series":[{"series_id":"anonymous-series","records":[...]}],"models":["seasonal_naive","grokked_sarima"],"horizon_months":12}' onChange={e=>setBulkInput(e.target.value)}/></label><Note>Forecasts: 1–10 series, 12 complete months for seasonal naive and 36 for Grokked/SARIMA. Benchmarks: 1–3 grid/wholesale series with 72 complete months. Units, coverage and monthly dates are mandatory. Archived transformer/Astra scores do not run customer inference.</Note><label className="upload"><Upload size={18}/><b>Load bulk JSON or a monthly CSV</b><input type="file" accept=".json,.csv" onChange={e=>{const f=e.target.files[0];if(!f)return;if(f.size>2000000){onError('Normalized JSON/CSV limit is 2 MB.');return;}run(async()=>{if(f.name.endsWith('.json'))setBulkInput(await f.text());else{let parsed=Papa.parse(await f.text(),{header:true,skipEmptyLines:true});if(parsed.errors.length)throw Error(parsed.errors[0].message);setBulkInput(JSON.stringify({series:[{series_id:'uploaded-series',kind:'demand',records:parsed.data}],models:['seasonal_naive','grokked_sarima'],horizon_months:12},null,2));}});e.target.value='';}}/></label></>}<button className="primary full" disabled={busy||(mode==='switching'&&(!profiles.length||!reviewed))} onClick={()=>run(submit)}><Play size={16}/>Queue analysis<ArrowRight size={15}/></button>{job&&<div className="job-status"><span className="status-dot"/>Analysis: {job.state}<button className="text-button" onClick={()=>run(()=>poll(job.job_id,'analysis'))}><RefreshCw size={14}/>Refresh</button></div>}<Note>Results use a private unguessable link and expire after one hour or a Space restart. Download the audit ZIP to retain them. One CPU worker; no paid model calls or automatic supplier switching.</Note></section></div>
{profiles.length>0&&<section className="panel"><div className="section-title"><div><h2>Imported electricity profiles</h2><p>Annualized historical scenarios; no missing latest-year bills are invented.</p></div><button className="secondary" onClick={()=>run(async()=>setHistory(await api('/api/provider_history',{import_job_id:importJob.job_id})))}>Inspect observed tariff evolution</button></div><SmallTable rows={profiles} fields={[["profile_id","Anonymous meter"],["provider","Provider"],["contracted_power_kva","Power · kVA"],["period_start","Start"],["period_end","End"],["observed_kwh","Observed · kWh"],["observed_electricity_charges","Electricity charges"],["annual_kwh","Annualized · kWh"],["current_annual_bill","Annualized cost"]]}/><div className="button-row">{profiles.map(p=><button className="text-button" key={p.profile_id} disabled={!reviewed||p.annual_kwh==null} onClick={()=>onProfile(p)}>Use {p.profile_id.slice(-6)} in Quote explorer <ArrowRight size={13}/></button>)}</div><details><summary>Allocated months and source checksums</summary><pre className="json">{JSON.stringify(profiles,null,2)}</pre></details></section>}
{history&&<section className="panel"><h2>Observed provider price evolution</h2>{history.groups.map(g=><div key={g.tariff_id} className="history-group"><h3>{g.provider} · {g.tariff_id.slice(-8)}</h3><p>{g.tax_included?'VAT included':'Before VAT'} · {g.unit} · historical observations</p><SmallTable rows={g.observations} fields={[["effective_from","Effective from"],["observed_at","Bill period end"],["rate_per_kwh","Unit price"],["date_basis","Date precision"]]}/></div>)}<Note>{history.limits}</Note></section>}
{result&&<section className="panel"><div className="section-title"><div><h2>Completed analysis</h2><p>{result.status}</p></div><a className="secondary" href={job.export_path} download><Download size={15}/>Private result audit ZIP</a></div>{plans.length>0&&<><SmallTable rows={plans} fields={[["profile_id","Profile"],["scenario","Price scenario"],["horizon_months","Months"],["planned_cost","Planned cost"],["stay_cost","Stay cost"],["saving_vs_stay_scenario","Scenario saving"],["currency","Currency"],["switch_count","Swaps"]]}/><Note>Exact minima within supplied monthly assumptions. Future prices and availability are uncertain; the full schedule shows fees, credits, guarantees and assumptions. This does not execute a switch.</Note></>}<details open={!plans.length}><summary>Full results, schedules and model diagnostics</summary><pre className="json">{JSON.stringify(result,null,2)}</pre></details></section>}
<section className="panel"><h2>Additional provider tariff history</h2><p>Import dated observations for other providers. Tariff IDs and VAT bases remain separate.</p><a className="text-button" href="/downloads/provider_history_template.csv" download>History CSV template <Download size={13}/></a><label className="upload"><Upload size={18}/><b>Inspect provider history CSV / JSON</b><input aria-label="Upload provider tariff history" type="file" accept=".csv,.json" onChange={e=>{const f=e.target.files[0];if(!f)return;if(f.size>2000000){onError('History limit is 2 MB.');return;}run(async()=>{const text=await f.text();let records;if(f.name.endsWith('.json')){const data=JSON.parse(text);records=Array.isArray(data)?data:data.records;}else{const parsed=Papa.parse(text,{header:true,skipEmptyLines:true});if(parsed.errors.length)throw Error(parsed.errors[0].message);records=parsed.data;}setHistory(await api('/api/provider_history',{records}));});e.target.value='';}}/></label></section><AuditDatasets/></>;
}