In this section
- Renewable Energy Planning Database (REPD) Verify Release automation · globalgrid2050 / automation/repd/verify_release.py lines 440–541
- Browser render · globalgrid2050 / automation/repd_expand_ui/browser.mjs lines 1–112
- Expand render · globalgrid2050 / automation/repd_expand_ui/expand.css lines 1–11
- Expand render · globalgrid2050 / automation/repd_expand_ui/expand.mjs lines 1–102
- Verify V976 other · globalgrid2050 / automation/repd_mobile/v976/verify_v976.py lines 1–42
- Build V974 storage · globalgrid2050 / automation/repd_reporting/v2/build-v974.mjs lines 1–139
- Cockpit Facets transform · globalgrid2050 / automation/repd_reporting/v2/cockpit-facets.mjs lines 1–192
Renewable Energy Planning Database (REPD) Verify Release
A Python command-line tool in the automation folder of GlobalGrid2050 that reads the REPD register and solar, using SHA-256.
automationglobalgrid2050 / automation/repd/verify_release.py · lines 440–541 of 541 (continued from section 837) · Entry point · pattern norm_text (shared by 3 files)
- What it does
- It loads the REPD register and solar. Defines 27 functions or classes, including nh, parse_text_date, swap_dm, excel_serial_to_date, sha256. Uses libraries argparse, collections, csv, datetime, hashlib. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar.
- Inputs & outputs
- In: command-line arguments. Out: JSON file.
- Downstream impact
- Used directly by 2 files: Test Validate (globalgrid2050); Renewable Energy Planning Database (REPD) Validate (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Test Hardening Nl013 (globalgrid2050).
- What it achieves
- It parses text date (`parse_text_date`), cleans ref (`clean_ref`) and checks CSV (`check_csv`). Independent integrity check of a raw official REPD release. It accepts `--xlsx`, `--sheet` and `--asof`.
- Why it matters
- Imported by Renewable Energy Planning Database (REPD) Validate. Checked by Test Validate.
- Application
- globalgrid2050 · automation/repd · Python CLI
- Uses
- argparse, collections, csv, datetime, hashlib, io, json, re
- Used by
- imported by Test Validate (sys.path import), imported by Renewable Energy Planning Database (REPD) Validate (relative import)
- Produces
- nh, parse_text_date, swap_dm, excel_serial_to_date, sha256, norm_text, as_number, clean_ref, Report, check_csv, idx, header_report
- Defines here
- check_expectations, one, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd/verify_release.py:440-541 · blob 6db4c3f0787336562b723b1b959fd2b2092f9269 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
rep.put('compare.base_rate_event_date_later_than_record_last_updated_in_csv', {k: v for k, v in c.get('base', {}).items() if k in per_col})
rep.note(' Base rate above: how often, across the whole CSV, a date in that column is later than the same record\'s "Record Last Updated". If that is common, "later than last update" is weak evidence.')
rep.note(' Plausibility is evidence only (an event dated after the record was last updated, or after the as-of date, is implausible); it is not an adjudication of the true date.')
# ---- silent ambiguity: dates that agree but whose day/month swap is also valid are not flagged (they agree)
# ---- non-date columns
other = collections.OrderedDict()
for col in [h for h in c['hn'] if h in x['hn'] and h not in DATE_COLUMNS]:
cls = collections.Counter(); ex = []
for ci, xi, ref in pairs:
a = c['dicts'][ci].get(col, '') or ''; cell = x['dicts'][xi][col]; b = x['render'](cell)
if a == b: continue
na, nb = norm_text(a), norm_text(b)
fa, fb = as_number(a), as_number(b)
if na == nb: k = 'whitespace/control-code only'
elif fa is not None and fb is not None and fa == fb: k = 'numeric formatting only'
elif fa is not None and fb is not None and abs(fa - fb) <= 0.005 + 1e-12: k = 'numeric rounding (<=0.005)'
elif na.upper() in ('', 'NA', 'N/A') and nb.upper() in ('', 'NA', 'N/A'): k = 'missing-value marker'
elif na.lstrip('0') == nb.lstrip('0') and na and nb: k = 'leading zeros'
else:
k = 'MATERIAL'
if len(ex) < rep.n: ex.append({'ref': ref, 'csv': a[:80], 'xlsx': b[:80]})
cls[k] += 1
if cls: other[col] = {'classes': dict(cls), 'material_examples': ex}
rep.put('compare.non_date_field_differences', other)
rep.put('compare.non_date_material_total', sum(v['classes'].get('MATERIAL', 0) for v in other.values()))
return conflicts
# ------------------------------------------------------------------ expectations
def check_expectations(exp, rep):
rep.section('Expectations (compared, not assumed)')
res = []
def one(label, expected, actual):
ok = expected == actual
res.append({'check': label, 'expected': expected, 'actual': actual, 'pass': ok})
rep.note(f" {'PASS' if ok else 'FAIL'} {label}: expected {expected!r}, actual {actual!r}")
g = rep.data.get
if exp.get('csv_bytes') is not None: one('CSV bytes', exp['csv_bytes'], g('csv.bytes'))
if exp.get('csv_sha256'): one('CSV sha256', exp['csv_sha256'].lower(), g('csv.sha256'))
if exp.get('rows') is not None: one('CSV rows', exp['rows'], g('csv.rows'))
if exp.get('unique_refs') is not None: one('CSV unique refs', exp['unique_refs'], g('csv.unique_refs'))
if exp.get('duplicate_refs') is not None:
one('CSV duplicated refs', sorted(exp['duplicate_refs']), sorted(d['ref'] for d in (g('csv.duplicate_refs') or {}).get('detail', [])))
if 'xlsx.bytes' in rep.data:
if exp.get('xlsx_bytes') is not None: one('XLSX bytes', exp['xlsx_bytes'], g('xlsx.bytes'))
if exp.get('xlsx_sha256'): one('XLSX sha256', exp['xlsx_sha256'].lower(), g('xlsx.sha256'))
if exp.get('rows') is not None: one('XLSX rows', exp['rows'], g('xlsx.rows'))
if exp.get('unique_refs') is not None: one('XLSX unique refs', exp['unique_refs'], g('xlsx.unique_refs'))
if exp.get('duplicate_refs') is not None:
one('XLSX duplicated refs', sorted(exp['duplicate_refs']), sorted(d['ref'] for d in (g('xlsx.duplicate_refs') or {}).get('detail', [])))
elif any(exp.get(k) for k in ('xlsx_bytes', 'xlsx_sha256')):
rep.note(' NOT CHECKED XLSX expectations (no --xlsx given)')
if exp.get('date_conflicts') is not None:
if 'compare.date_disagreements.detail' in rep.data:
actual = collections.defaultdict(list)
for d in rep.data['compare.date_disagreements.detail']: actual[d['field']].append(d['ref'])
want = {nh(k): sorted(v, key=int) for k, v in exp['date_conflicts'].items()}
one('CSV-vs-XLSX date disagreements (field -> refs), complete list', want, {k: sorted(v, key=lambda r: int(r) if r.isdigit() else 0) for k, v in actual.items()})
else:
rep.note(' NOT CHECKED date-conflict expectation (needs --xlsx)')
rep.data['expectations'] = res
return all(r['pass'] for r in res)
def main(argv=None):
ap = argparse.ArgumentParser(description='Verify a raw official REPD CSV (and optionally the XLSX).')
ap.add_argument('csv'); ap.add_argument('--xlsx'); ap.add_argument('--sheet')
ap.add_argument('--asof', default=datetime.date.today().isoformat(), help='reference date for "future" and plausibility tests (YYYY-MM-DD)')
ap.add_argument('--json'); ap.add_argument('--max-examples', type=int, default=10)
ap.add_argument('--expect-october-2026', action='store_true', help='compare against the figures reported for the October 2026 (Q3) files')
ap.add_argument('--expect-csv-bytes', type=int); ap.add_argument('--expect-csv-sha256')
ap.add_argument('--expect-xlsx-bytes', type=int); ap.add_argument('--expect-xlsx-sha256')
ap.add_argument('--expect-rows', type=int); ap.add_argument('--expect-unique-refs', type=int)
ap.add_argument('--expect-duplicate-refs', help='comma-separated refs expected to be duplicated ("" for none)')
ap.add_argument('--expect-date-conflicts', action='append', help='"Field name=ref,ref" (repeatable); the complete expected list')
a = ap.parse_args(argv)
asof = datetime.date.fromisoformat(a.asof)
exp = dict(OCTOBER_2026) if a.expect_october_2026 else {}
for k in ('csv_bytes', 'csv_sha256', 'xlsx_bytes', 'xlsx_sha256', 'rows', 'unique_refs'):
v = getattr(a, 'expect_' + k)
if v is not None: exp[k] = v
if a.expect_duplicate_refs is not None: exp['duplicate_refs'] = [r for r in a.expect_duplicate_refs.split(',') if r.strip()]
if a.expect_date_conflicts:
exp['date_conflicts'] = {f.split('=', 1)[0]: [r.strip() for r in f.split('=', 1)[1].split(',') if r.strip()] for f in a.expect_date_conflicts}
rep = Report(a.max_examples)
rep.put('tool', 'verify_release.py'); rep.put('asof', str(asof))
c = check_csv(a.csv, asof, rep)
x = check_xlsx(a.xlsx, a.sheet, rep) if a.xlsx else None
if c and x: compare(c, x, asof, rep)
ok = check_expectations(exp, rep) if exp else True
rep.section('Result')
rep.put('structural_errors', rep.structural)
status = 2 if rep.structural else (0 if ok else 1)
rep.put('exit_status', status)
rep.note({0: 'OK: no structural error and no failed expectation.', 1: 'EXPECTATION FAILED: see the Expectations section.',
2: 'STRUCTURAL ERROR: see the STRUCTURAL lines above.'}[status])
print('\n'.join(rep.lines))
if a.json:
with open(a.json, 'w', encoding='utf-8') as f:
json.dump(rep.data, f, indent=1, default=str, ensure_ascii=False)
return status
if __name__ == '__main__':
sys.exit(main())Browser
A JavaScript module in the REPD expand ui folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register.
renderglobalgrid2050 / automation/repd_expand_ui/browser.mjs · lines 1–112 of 112 · Entry point
- What it does
- It draws the REPD register. Uses libraries node:assert/strict, node:http, node:fs, node:path, node:url. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Inputs & outputs
- Out: JSON file receipt.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 V934 Preview Acceptance Workflow (globalgrid2050).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by GlobalGrid2050 V934 Preview Acceptance Workflow.
- Application
- globalgrid2050 · automation/repd_expand_ui · JavaScript module
- Uses
- node:assert/strict, node:http, node:fs, node:path, node:url
- Used by
- run by GlobalGrid2050 V934 Preview Acceptance Workflow (workflow run)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd_expand_ui/browser.mjs:1-112 · blob c7bd57b00727a642b9874d51e7a19dd3240bd7bf · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {readFileSync,writeFileSync,mkdirSync} from 'node:fs';
import {resolve,extname,sep} from 'node:path';
import {pathToFileURL} from 'node:url';
const ownRoot=resolve(import.meta.dirname,'../..');
const root=resolve(process.env.REPD_EXPAND_ROOT||ownRoot);
const edition=process.env.REPD_EXPAND_EDITION||'uk_renewables_pipeline/202611170512';
const out=resolve(process.env.REPD_EXPAND_OUT||'D:/githubfiles/.qa-artifacts/repd-expand-agent-b');
const {chromium}=await import(process.env.PLAYWRIGHT_MODULE?pathToFileURL(process.env.PLAYWRIGHT_MODULE).href:'playwright');
mkdirSync(out,{recursive:true});
const css='/automation/repd_expand_ui/expand.css',js='/automation/repd_expand_ui/expand.mjs';
const server=createServer((req,res)=>{
try{
let path=decodeURIComponent(new URL(req.url,'http://local').pathname);
if(path.endsWith('/'))path+='index.html';
const sourceRoot=[css,js].includes(path)?ownRoot:root;
const file=resolve(sourceRoot,'.'+path);
assert.ok(file.startsWith(sourceRoot+sep));
let bytes=readFileSync(file);
if(path==='/'+edition+'/index.html'){
let html=bytes.toString();
if(!html.includes('repd_expand_ui/expand.css'))html=html.replace('</head>',`<link rel="stylesheet" href="${css}"></head>`);
if(!html.includes('repd_expand_ui/expand.mjs'))html=html.replace('</body>',`<script type="module" src="${js}"></script></body>`);
bytes=Buffer.from(html);
}
res.setHeader('Content-Type',({'.mjs':'text/javascript','.js':'text/javascript','.css':'text/css','.json':'application/json','.html':'text/html'})[extname(file)]||'application/octet-stream');
res.end(bytes);
}catch{res.writeHead(404).end();}
});
await new Promise(r=>server.listen(0,'127.0.0.1',r));
const origin='http://127.0.0.1:'+server.address().port;
const proof={status:'RUNNING',edition,checks:[],limitations:['Local Chromium/touch emulation; physical handset and public deployment unverified.','External requests blocked; existing source data and local scripts used.']};
let browser;
try{
browser=await chromium.launch({headless:true});
for(const width of [390,393,1440]){
const context=await browser.newContext({viewport:{width,height:844},isMobile:width<500,hasTouch:width<500});
await context.route('**/*',route=>route.request().url().startsWith(origin)?route.continue():route.abort());
const page=await context.newPage();
await page.goto(origin+'/'+edition+'/index.html?technology=all');
await page.waitForFunction(()=>Number(document.querySelector('#tbody')?.dataset.total)===7775);
const trigger=page.locator('[data-repd-expand]'),modal=page.locator('.repd-expand-dialog');
await page.locator('#search').fill('15149');
await page.locator('#repd-15149').waitFor();
await page.evaluate(()=>{window.originalRegister=document.querySelector('#officialRegister');window.originalRow=document.querySelector('#repd-15149');window.originalParent=originalRegister.parentElement;});
const mapBefore=await page.locator('#repd-15149 .map-action, #repd-15149 a').first().getAttribute('href');
await trigger.scrollIntoViewIfNeeded();
const scrollBefore=await page.evaluate(()=>scrollY);
await trigger.click();
await modal.waitFor({state:'visible'});
assert.equal(await trigger.getAttribute('aria-expanded'),'true');
assert.equal(await page.evaluate(()=>document.activeElement.classList.contains('repd-expand-close')),true);
assert.equal(await page.evaluate(()=>document.querySelector('dialog #officialRegister')===originalRegister&&document.querySelector('#repd-15149')===originalRow),true);
const bounds=await modal.boundingBox();
assert.ok(Math.abs(bounds.x)<2&&Math.abs(bounds.y)<2&&Math.abs(bounds.width-width)<2&&Math.abs(bounds.height-844)<2,JSON.stringify(bounds));
assert.equal(await page.locator('#search').inputValue(),'15149');
await page.keyboard.press('Shift+Tab');
assert.equal(await page.evaluate(()=>document.activeElement.closest('.repd-expand-dialog')!==null),true);
const downloaded=page.waitForEvent('download');
await page.locator('#exportInline').click();
const download=await downloaded;assert.match(readFileSync(await download.path(),'utf8'),/15149/);
// A second modal (for example a source note) closes before analytics does.
await page.evaluate(()=>{const note=document.createElement('dialog');note.id='testNote';note.textContent='Nested note';document.body.append(note);note.showModal();});
await page.keyboard.press('Escape');
await page.waitForFunction(()=>!document.querySelector('#testNote').open);
assert.equal(await modal.evaluate(n=>n.open),true);
await page.evaluate(()=>document.querySelector('#testNote').remove());
await page.locator('.repd-expand-close').click();
await page.waitForFunction(()=>!document.querySelector('.repd-expand-dialog').open&&document.querySelector('#officialRegister')?.parentElement===originalParent);
assert.equal(await page.evaluate(()=>document.querySelector('#officialRegister')===originalRegister&&originalRegister.parentElement===originalParent),true);
assert.equal(await trigger.getAttribute('aria-expanded'),'false');
assert.equal(await trigger.evaluate(n=>document.activeElement===n),true);
assert.ok(Math.abs(await page.evaluate(()=>scrollY)-scrollBefore)<3);
assert.equal(await page.evaluate(()=>document.documentElement.style.overflow),'');
assert.equal(await page.locator('#search').inputValue(),'15149');
assert.equal(await page.locator('#repd-15149 .map-action, #repd-15149 a').first().getAttribute('href'),mapBefore);
// Repeat, pan the live table, rotate, then close with Escape.
await trigger.click();
await page.locator('.repd-expand-dialog .tablewrap').evaluate(n=>n.scrollLeft=200);
const pan=await page.locator('.repd-expand-dialog .tablewrap').evaluate(n=>n.scrollLeft);
if(width<500){
await page.setViewportSize({width:915,height:412});
const landscape=await modal.boundingBox();assert.ok(Math.abs(landscape.width-915)<2&&Math.abs(landscape.height-412)<2);
await page.locator('.repd-expand-close').scrollIntoViewIfNeeded();
assert.ok(await page.locator('.repd-expand-close').isVisible());
await page.setViewportSize({width,height:844});
}
await page.screenshot({path:resolve(out,`expanded-${width}.png`)});
await page.keyboard.press('Escape');
await page.waitForFunction(()=>!document.querySelector('.repd-expand-dialog').open&&document.querySelector('#officialRegister')?.parentElement===originalParent);
assert.equal(await page.locator('#officialRegister .tablewrap').evaluate(n=>n.scrollLeft),pan);
assert.equal(await page.evaluate(()=>document.querySelectorAll('#officialRegister').length),1);
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));
proof.checks.push({width,status:'PASS',checks:['viewport coverage','same live nodes','search/CSV/MAP preserved','focus containment/return','close and Escape','nested modal Escape','scroll restoration','repeat open/close','table pan retained',...(width<500?['portrait-landscape-return']:[])]});
await context.close();
}
const fallback=await browser.newContext({viewport:{width:390,height:844}});
await fallback.route('**/*',route=>route.request().url().startsWith(origin)?route.continue():route.abort());
await fallback.addInitScript(()=>{HTMLDialogElement.prototype.showModal=undefined;});
const fallbackPage=await fallback.newPage();
await fallbackPage.goto(origin+'/'+edition+'/index.html?technology=all');
await fallbackPage.waitForFunction(()=>Number(document.querySelector('#tbody')?.dataset.total)===7775);
assert.equal(await fallbackPage.locator('[data-repd-expand]').count(),0);
assert.equal(await fallbackPage.locator('#officialRegister').isVisible(),true);
proof.checks.push({status:'PASS',checks:['unsupported modal API retains ordinary dashboard']});
await fallback.close();
proof.status='PASS';
}catch(error){proof.status='FAIL';proof.error=String(error.stack||error);throw error;}
finally{if(browser)await browser.close();await new Promise(r=>server.close(r));writeFileSync(resolve(out,'receipt.json'),JSON.stringify(proof,null,2));}
console.log(JSON.stringify(proof,null,2));Expand
A style sheet in the REPD expand ui folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register.
renderglobalgrid2050 / automation/repd_expand_ui/expand.css · lines 1–11 of 11 · Entry point
- What it does
- Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents); A4 Legal Model (globalgrid2050).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/.
- Application
- globalgrid2050 · automation/repd_expand_ui · style sheet
- Uses
- none found
- Used by
- loaded by GlobalGrid2050 — UK Renewables Pipeline Page (stylesheet)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd_expand_ui/expand.css:1-11 · blob cae9ae912ab1c73d34746d24294c0bfc7e2da467 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
.repd-expand-launcher{display:flex;justify-content:flex-end;margin:0 0 10px}
.repd-expand-open,.repd-expand-close{min-height:44px;color:var(--accent,#0ff);touch-action:manipulation}
.repd-expand-dialog{position:fixed;inset:0;margin:0;border:0;padding:0;width:100%;max-width:none;height:100vh;height:100dvh;max-height:none;background:#000;color:var(--text,#fff);overflow:hidden;overscroll-behavior:none;box-sizing:border-box}
.repd-expand-dialog[open]{display:flex;flex-direction:column}
.repd-expand-dialog::backdrop{background:#000}
.repd-expand-bar{flex:none;display:flex;align-items:center;justify-content:space-between;gap:8px;border-bottom:1px solid var(--line,#333);background:#000;padding:8px 12px;padding-top:max(8px,env(safe-area-inset-top));padding-right:max(12px,env(safe-area-inset-right));padding-left:max(12px,env(safe-area-inset-left));font:700 11px 'Courier New',monospace;color:var(--accent,#0ff)}
.repd-expand-dialog #officialRegister{flex:1;min-height:0;margin:0;padding:12px;padding-right:max(12px,env(safe-area-inset-right));padding-bottom:max(12px,env(safe-area-inset-bottom));padding-left:max(12px,env(safe-area-inset-left));overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable}
.repd-expand-dialog .repd-expand-launcher{display:none}
.repd-expand-dialog .tablewrap{max-height:75vh;max-height:75dvh;overscroll-behavior:contain}
.repd-expand-dialog button:focus-visible{outline:2px solid var(--solar,#ff0);outline-offset:2px}
@media(max-width:768px){.repd-expand-bar span{font-size:10px;max-width:40%}.repd-expand-close{font-size:10px;padding:8px}.repd-expand-dialog .gauges{grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}.repd-expand-dialog .card{padding:8px 3px}.repd-expand-dialog .card h3{font-size:8px}.repd-expand-dialog .chart{height:65px}.repd-expand-dialog .value{font-size:16px}}Expand
A JavaScript module in the REPD expand ui folder of GlobalGrid2050 that mounts Renewable Energy Planning Database (REPD) expansion (`mountRepdExpansion`) and restores positions (`restorePositions`), covering the REPD register.
renderglobalgrid2050 / automation/repd_expand_ui/expand.mjs · lines 1–102 of 102 · Entry point · pattern restore (shared by 8 files)
- What it does
- It draws the REPD register. Defines mountRepdExpansion, scrollPositions, restorePositions, restore. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 — UK Renewables Pipeline Page (globalgrid2050, https://globalgrid2050.com/uk_renewables_pipeline/202611280922/). Reached from 4 other entry points, including GlobalGrid2050 Pipeline Legal Evidence Workflow (globalgrid2050); V923 Public Readback Workflow (neural-link-between-agents); A4 Legal Model (globalgrid2050).
- What it achieves
- It restores positions (`restorePositions`) and is built from the mount REPD expansion helper (`mountRepdExpansion`) and the scroll positions helper (`scrollPositions`). Expand the existing analytics nodes; never clone data, controls or listeners. It responds to click, cancel and keydown events.
- Why it matters
- Loaded by the UK Renewables Pipeline page at https://globalgrid2050.com/uk_renewables_pipeline/202611280922/.
- Application
- globalgrid2050 · automation/repd_expand_ui · JavaScript module
- Uses
- none found
- Used by
- loaded by GlobalGrid2050 — UK Renewables Pipeline Page (script src)
- Produces
- mountRepdExpansion
- Defines here
- mountRepdExpansion, scrollPositions, restorePositions, restore
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd_expand_ui/expand.mjs:1-102 · blob ee2eff9092a8d089bde80359593a08ce6382fd80 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/** Expand the existing analytics nodes; never clone data, controls or listeners. */
export function mountRepdExpansion(doc = document) {
const section = doc.getElementById('officialRegister');
if (!section || section.querySelector('[data-repd-expand]')) return null;
const dialog = doc.createElement('dialog');
// An unsupported browser keeps its ordinary, usable dashboard.
if (typeof dialog.showModal !== 'function') return null;
dialog.className = 'repd-expand-dialog';
dialog.setAttribute('aria-label', 'REPD pipeline analytics expanded view');
const bar = doc.createElement('div');
bar.className = 'repd-expand-bar';
const title = doc.createElement('span');
title.textContent = 'REPD PIPELINE ANALYTICS';
const close = doc.createElement('button');
close.type = 'button';
close.className = 'btn repd-expand-close';
close.textContent = 'CLOSE EXPANDED VIEW';
close.setAttribute('aria-label', 'Close expanded REPD analytics and return to page');
bar.append(title, close);
dialog.append(bar);
const trigger = doc.createElement('button');
trigger.type = 'button';
trigger.className = 'btn repd-expand-open';
trigger.dataset.repdExpand = '';
trigger.textContent = 'EXPAND ANALYTICS';
trigger.setAttribute('aria-haspopup', 'dialog');
trigger.setAttribute('aria-expanded', 'false');
const launcher = doc.createElement('div');
launcher.className = 'repd-expand-launcher';
launcher.append(trigger);
const heading = section.querySelector('#pipelineHeading');
if (heading) heading.after(launcher);
else section.prepend(launcher);
doc.body.append(dialog);
let marker = null;
let saved = null;
let closingPositions = null;
const win = doc.defaultView;
const scrollPositions = () => [...section.querySelectorAll('*')]
.filter(node => node.scrollLeft || node.scrollTop)
.map(node => ({ node, left: node.scrollLeft, top: node.scrollTop }));
const restorePositions = (positions) => positions.forEach(({node,left,top}) => {
node.scrollLeft = left;
node.scrollTop = top;
});
function restore() {
if (!marker) return;
const positions = closingPositions || scrollPositions();
closingPositions = null;
marker.replaceWith(section);
marker = null;
doc.documentElement.style.overflow = saved.htmlOverflow;
doc.body.style.overflow = saved.bodyOverflow;
trigger.setAttribute('aria-expanded', 'false');
restorePositions(positions);
trigger.focus({ preventScroll: true });
win.scrollTo(saved.x, saved.y);
}
trigger.addEventListener('click', () => {
if (dialog.open) return;
saved = { x: win.scrollX, y: win.scrollY,
htmlOverflow: doc.documentElement.style.overflow,
bodyOverflow: doc.body.style.overflow };
marker = doc.createComment('REPD analytics return position');
const positions = scrollPositions();
section.before(marker);
dialog.append(section);
try {
dialog.showModal();
restorePositions(positions);
doc.documentElement.style.overflow = 'hidden';
doc.body.style.overflow = 'hidden';
trigger.setAttribute('aria-expanded', 'true');
close.focus({ preventScroll: true });
} catch (error) {
restore();
// Leave the normal dashboard usable if modal display is unavailable.
console.warn('REPD expanded view unavailable', error);
}
});
close.addEventListener('click', () => {
closingPositions = scrollPositions();
dialog.close();
});
dialog.addEventListener('cancel', () => { closingPositions = scrollPositions(); });
dialog.addEventListener('keydown', (event) => {
if (event.key !== 'Tab') return;
const items = [...dialog.querySelectorAll('button,input,select,textarea,a[href],summary,[tabindex]')]
.filter(node => !node.disabled && node.tabIndex >= 0 && node.getClientRects().length);
const first = items[0], last = items.at(-1);
if ((event.shiftKey && doc.activeElement === first)
|| (!event.shiftKey && doc.activeElement === last)) {
event.preventDefault();
(event.shiftKey ? last : first).focus();
}
});
// Native Escape/cancel also fires close. Nested note dialogs retain their own Escape.
dialog.addEventListener('close', restore);
return { dialog, trigger, close };
}
if (typeof document !== 'undefined') mountRepdExpansion();Verify V976
A Python module in the REPD mobile folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register, using SHA-256.
otherglobalgrid2050 / automation/repd_mobile/v976/verify_v976.py · lines 1–42 of 42 · Entry point
- What it does
- Uses libraries hashlib, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Renewable Energy Planning Database (REPD) Mobile V976 Workflow (globalgrid2050).
- What it achieves
- V9.76 full source-closure and no-truncation acceptance; original REPD palette is immutable.
- Why it matters
- Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Mobile V976 Workflow.
- Application
- globalgrid2050 · automation/repd_mobile/v976 · Python module
- Uses
- hashlib, pathlib
- Used by
- run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Mobile V976 Workflow (workflow run)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd_mobile/v976/verify_v976.py:1-42 · blob 0acf8d78cab3745ef19a2e01f0a33fab46916fb8 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""V9.76 full source-closure and no-truncation acceptance; original REPD palette is immutable."""
import hashlib
from pathlib import Path
ROOT=Path(__file__).resolve().parents[3]
OLD=ROOT/"uk_renewables_pipeline/202611231600"
NEW=ROOT/"uk_renewables_pipeline/202611232245"
a={str(p.relative_to(OLD)):p.read_bytes() for p in OLD.rglob("*") if p.is_file()}
b={str(p.relative_to(NEW)):p.read_bytes() for p in NEW.rglob("*") if p.is_file()}
assert len(a)==345,("Unexpected accepted V9.75 source inventory",len(a))
assert set(a).issubset(b),("TRUNCATED files",set(a)-set(b))
assert set(b)-set(a)=={"styles/repd-mobile-v976.css","tests/v976-mobile-browser.mjs"},(
"Unexpected release additions",set(b)-set(a))
changed={p for p in a if a[p]!=b[p]}
assert changed=={"index.html"},("Nonvisual source changed",changed)
for p in a:
if p=="index.html":continue
assert hashlib.sha256(a[p]).digest()==hashlib.sha256(b[p]).digest(),p
for p in ("styles/v7.css","styles/repd-reports.css","styles/repd-density.css",
"styles/hud-v955.css","styles/compact-register.css","styles/repd-scan.css",
"scripts/plugins/projects-v9-8.js","scripts/plugins/gauges-v9-2.js",
"repd-reports.mjs","repd-reports-model.mjs","report-a4.mjs","report-pdf.mjs",
"map-entry.mjs","repd-expanded.mjs"):
assert a[p]==b[p],("Original data/logic/SCADA palette not immutable",p)
html=b["index.html"].decode()
assert html.count('styles/repd-mobile-v976.css')==1
assert html.count('styles/repd-reports.css')==1
assert html.index('styles/repd-mobile-v976.css')>html.index('styles/repd-reports.css')
assert html.count('id="repdReportSwipeHint"')==1
assert "Pipeline News V9.76 · 202611232245" in html
assert "Cockpit" not in html and "COCKPIT" not in html
for id in ("repdReportsPanel","repdNativeStatus","repdNativeOperator",
"repdNativeRegion","status","repdScroll"):
assert html.count('id="'+id+'"')==1,id
css=b["styles/repd-mobile-v976.css"].decode()
for selector in ("@media (max-width:768px)","#repdPanel #repdReportsBody",
"#repdPanel #status.filters","white-space:nowrap!important",
"overflow-x:auto!important","width:760px!important"):
assert selector in css,("Mobile guard missing",selector)
assert not any(name in changed for name in ("map-entry.mjs","report-a4.mjs","report-pdf.mjs"))
print("PASS: V9.76 inherits",len(a),"immutable V9.75 files, 0 missing, 1 HTML link/hint changed, 2 additive CSS/browser test files; no original REPD colour, data, MAP, A4, PDF, or functional JS altered.")Build V974
A JavaScript module in the REPD reporting folder of GlobalGrid2050 that reads cockpit build receipt, the Renewable Energy Planning Database (REPD) register, solar and battery storage (BESS), using SHA-256.
storageglobalgrid2050 / automation/repd_reporting/v2/build-v974.mjs · lines 1–139 of 139 · Entry point · pattern inventory (shared by 18 files)
- What it does
- It loads cockpit build receipt, the REPD register, solar and battery storage (BESS). Defines sha, inventory, walk. Uses libraries node:fs/promises, node:path, node:url, node:crypto. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar, battery storage (BESS).
- Inputs & outputs
- In: JSON file build_manifest.json. Out: JSON file COCKPIT-BUILD-RECEIPT.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Pn V974 Cockpit Integration Workflow (globalgrid2050).
- What it achieves
- It is built from the sha step (`sha`), the inventory step (`inventory`) and the walk step (`walk`). Copy the FULL accepted V9.73 page, change only: index title, report controller, README, CHANGES, and add test+receipt.
- Why it matters
- Run by GlobalGrid2050 Pn V974 Cockpit Integration Workflow.
- Application
- globalgrid2050 · automation/repd_reporting/v2 · JavaScript module
- Uses
- node:fs/promises, node:path, node:url, node:crypto
- Used by
- run by GlobalGrid2050 Pn V974 Cockpit Integration Workflow (workflow run)
- Produces
- sha, inventory, walk
- Defines here
- sha, inventory, walk
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd_reporting/v2/build-v974.mjs:1-139 · blob 3b1c1e77cc4460fda4674472ab96518368f3f5b2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
* V9.74 candidate composer. Copy the FULL accepted V9.73 page, change only:
* index title, report controller, README, CHANGES, and add test+receipt.
* No source data, colors, existing CSS, MAP/A4, gauges or GridAtlas edits.
* Re-running with changed candidate bytes must fail, never overwrite.
*/
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createHash } from "node:crypto";
const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, "../../..");
const oldId = "202611222330";
const newId = "202611231400";
const oldDir = path.join(root, "uk_renewables_pipeline", oldId);
const newDir = path.join(root, "uk_renewables_pipeline", newId);
const sha = bytes => createHash("sha256").update(bytes).digest("hex");
async function inventory(folder) {
const items = new Map();
async function walk(directory) {
for (const entry of await fs.readdir(directory, { withFileTypes:true })) {
const full = path.join(directory,entry.name);
if (entry.isSymbolicLink()) throw new Error("Unreviewed symlink: " + full);
if (entry.isDirectory()) await walk(full);
else if (entry.isFile()) items.set(path.relative(folder,full).replaceAll("\\","/"),await fs.readFile(full));
else throw new Error("Unreviewed entry " + full);
}
}
await walk(folder);
return items;
}
if ((await fs.stat(oldDir)).isDirectory() !== true) throw new Error("Missing exact V9.73 source");
try {
await fs.stat(newDir);
throw new Error("Candidate path already exists; immutable release must not be replaced");
} catch(e) { if (e.code !== "ENOENT") throw e; }
const original = await inventory(oldDir);
if (original.size < 35) throw new Error("Source V9.73 unexpectedly truncated, only " + original.size + " files");
const mustProtect = [
"map-entry.mjs","report-a4.mjs","report-model.mjs","report-pdf.mjs",
"repd-expanded.mjs","scripts/plugins/projects-v9-8.js",
"scripts/plugins/preview-v928.js","styles/v7.css","styles/repd-reports.css",
"data/v9.1/build_manifest.json", "tests/v972-vicinity-a4-pdf.mjs"
];
for (const file of mustProtect) if (!original.has(file)) throw new Error("Missing protected V9.73 dependency: " + file);
const oldHtml = original.get("index.html").toString("utf8");
if (!oldHtml.includes("V9.73") || !oldHtml.includes(oldId) ||
!oldHtml.includes('src="repd-reports.mjs"') ||
!oldHtml.includes('data-repd-report="operator"')) {
throw new Error("V9.73 page identity/report mounting is not as expected");
}
const html = oldHtml.replace("V9.73", "V9.74").replace(oldId,newId);
const controller = await fs.readFile(path.join(here, "repd-reports-integrated.mjs"),"utf8");
const browserTest = await fs.readFile(path.join(here,"tests","v974-cockpit-browser.mjs"),"utf8");
for (const mark of [
'import { state } from "./scripts/core/state.js"',
'import { buildRepdCapacityReport } from "./repd-reports-model.mjs"',
'import { buildCockpitReport, SOURCE_UNAVAILABLE }',
'pipeline-projects-rendered', 'atlasUrlV9_5_1',
'buildAtlasInterconnectorLinkV9_8'
]) if (!controller.includes(mark)) throw new Error("Missing integration contract " + mark);
await fs.cp(oldDir,newDir,{recursive:true,errorOnExist:true,force:false});
await fs.writeFile(path.join(newDir,"index.html"),html);
await fs.writeFile(path.join(newDir,"repd-reports.mjs"),controller);
await fs.writeFile(path.join(newDir,"README.md"),[
"# V9.74 — Technology-aware REPD operator, status and region cockpit",
"",
"Full immutable successor of V9.73 ("+oldId+").",
"The SAME existing REPD cockpit now ranks operators by the selected technology.",
"Solar shows solar-only MWp and operators; BESS, onshore and offshore use their own MW.",
"A status facet covers every original REPD status, including refused, withdrawn",
"and not reported. Operator and region facets intersect; switching report buttons",
"retains selections. Current Table Filters remains an explicit, separate scope.",
"Interconnectors retain their own inventory and are never added to 7,775 REPD records.",
"Grid reporting awaits a verified separate source. No measured energy claims.",
"",
"No changes to published V9.73, data, styling, colours, original chart gauges,",
"ticker, navigation, REPD source, MAP/A4/PDF/expanded view or GridAtlas.",
"Only index.html (version title), repd-reports.mjs, README.md and CHANGES.md",
"differ from V9.73, plus the new browser test and build receipt.",
"",
"Rollback remains /uk_renewables_pipeline/"+oldId+"/.",
""
].join("\n"));
await fs.writeFile(path.join(newDir,"CHANGES.md"),[
"# V9.74 candidate: REPD cockpit cross-filter integration",
"",
"- Existing Operator MW / Status MW / Region MW grouped reports respond to the same",
" Solar / BESS / Onshore / Offshore technology selection as the REPD table.",
"- Compact report-native status, operator and region facets, without resetting on",
" switching reports, give ranked operators by recorded selected-technology capacity.",
"- All official statuses remain selectable, including statuses absent from the",
" four fast table status buttons; missing labels stay explicit.",
"- Native per-project REPD drill-back and MAP/A4 navigation unchanged.",
"- Interconnector source kept separate from REPD, not combined in ALL TECH.",
"- All original CSS, gauge, ticker, GridAtlas and core data bytes unchanged.",
""
].join("\n"));
await fs.writeFile(path.join(newDir,"tests","v974-cockpit-browser.mjs"),browserTest);
const after = await inventory(newDir);
const changed = [], missing=[];
for (const [rel,originalBytes] of original) {
const newBytes=after.get(rel);
if (!newBytes) {missing.push(rel);continue;}
if (!originalBytes.equals(newBytes)) changed.push(rel);
}
const expectedChanged=["index.html","repd-reports.mjs","README.md","CHANGES.md"].sort();
if (missing.length || JSON.stringify(changed.sort()) !== JSON.stringify(expectedChanged)) {
throw new Error("Copied edition's inherited file diff is not exact: " +
JSON.stringify({missing,changed,expectedChanged}));
}
const added=[...after.keys()].filter(x=>!original.has(x)).sort();
if (JSON.stringify(added)!==JSON.stringify(["tests/v974-cockpit-browser.mjs"])) {
throw new Error("Unreviewed new file additions " + JSON.stringify(added));
}
const immutable = [...original.entries()].filter(([name])=>!expectedChanged.includes(name));
const receipt = {
schema:"ventus.pipeline.cockpit-v974-receipt.v1",
originalRelease:oldId, newRelease:newId,
originalFileCount:original.size,
inheritedUnchangedCount:immutable.length,
missingFiles:missing, changedFiles:changed, addedFiles:added,
inheritedManifestSha256:sha(Buffer.from(immutable.sort((a,b)=>a[0].localeCompare(b[0]))
.map(([rel,buf])=>rel+"\t"+sha(buf)+"\n").join(""))),
sourceCssSha256:sha(original.get("styles/v7.css")),
candidateCssSha256:sha(after.get("styles/v7.css")),
sourceReportCssSha256:sha(original.get("styles/repd-reports.css")),
candidateReportCssSha256:sha(after.get("styles/repd-reports.css")),
releaseAccepted:false, published:false,
status:"ISOLATED_UNVERIFIED_BROWSER_AND_PUBLIC",
};
await fs.writeFile(path.join(newDir,"COCKPIT-BUILD-RECEIPT.json"),JSON.stringify(receipt,null,2)+"\n");
console.log(JSON.stringify(receipt,null,2));Cockpit Facets
A JavaScript module in the REPD reporting folder of GlobalGrid2050 that works with interconnectors, the Renewable Energy Planning Database (REPD) register and solar.
transformglobalgrid2050 / automation/repd_reporting/v2/cockpit-facets.mjs · lines 1–192 of 192 · Entry point · pattern accumulate (shared by 2 files)
- What it does
- It calculates interconnectors, the REPD register and solar. Defines 16 functions or classes, including label, selected, cockpitSelection, identity, verifyInventory.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: interconnectors, the REPD register, solar.
- Downstream impact
- Used directly by 3 files: Cockpit Facets Test (globalgrid2050); GlobalGrid2050 Pn V974 Cockpit Integration Workflow (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Cockpit V2 Workflow (globalgrid2050).
- What it achieves
- It verifies inventory (`verifyInventory`) and builds cockpit report (`buildCockpitReport`). PipelineNews REPD cockpit cross-filter contract (candidate v2).
- Why it matters
- Run by GlobalGrid2050 Pn V974 Cockpit Integration Workflow and GlobalGrid2050 Renewable Energy Planning Database (REPD) Cockpit V2 Workflow. Checked by Cockpit Facets Test.
- Application
- globalgrid2050 · automation/repd_reporting/v2 · JavaScript module
- Uses
- none found
- Used by
- imported by Cockpit Facets Test (import), run by GlobalGrid2050 Pn V974 Cockpit Integration Workflow (workflow run), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Cockpit V2 Workflow (workflow run)
- Produces
- REPD_TECHNOLOGIES, COCKPIT_TECHNOLOGIES, REPORT_DIMENSIONS, SOURCE_UNAVAILABLE, UNKNOWN, cockpitSelection, verifyInventory, buildCockpitReport
- Defines here
- label, selected, cockpitSelection, identity, verifyInventory, technologyMatches, matches, mwScaled, unit, emptyTotals, accumulate, displayTotals, convert, grouped, facets, buildCockpitReport
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd_reporting/v2/cockpit-facets.mjs:1-192 · blob 866b10b30eaef6eb80259216acf24f0476b88a26 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
/**
* PipelineNews REPD cockpit cross-filter contract (candidate v2).
* Pure data module: no DOM, no networking, no source mutation, no publication.
* Canonical REPD and interconnectors remain separate datasets.
*/
export const REPD_TECHNOLOGIES = Object.freeze([
"all", "solar", "bess", "wind_onshore", "wind_offshore"
]);
export const COCKPIT_TECHNOLOGIES = Object.freeze([
...REPD_TECHNOLOGIES, "interconnector", "grid"
]);
export const REPORT_DIMENSIONS = Object.freeze([
"operator", "status", "region", "technology"
]);
export const SOURCE_UNAVAILABLE = "SOURCE_NOT_AVAILABLE";
export const UNKNOWN = "Not reported";
const DECIMAL_SCALE = 1_000_000;
function label(value) {
const string = value === null || value === undefined ? "" : String(value).trim();
return string || UNKNOWN;
}
function selected(value) {
return value === null || value === undefined || value === "" || value === "All" ? "All" : String(value);
}
export function cockpitSelection(filters = {}) {
const technology = filters.technology ?? "all";
if (!COCKPIT_TECHNOLOGIES.includes(technology)) {
throw new TypeError("Unsupported technology selection: " + technology);
}
return {
technology,
status: selected(filters.status),
operator: selected(filters.operator),
region: selected(filters.region),
};
}
function identity(row, source) {
const ref = source === "repd"
? row?.repd_ref
: row?.asset_id ?? row?.gg_project_id ?? row?.bmrs_code;
const id = ref === undefined || ref === null ? "" : String(ref).trim();
if (!id || (source === "repd" && !/^\d+$/.test(id))) {
throw new Error("Missing or invalid " + source + " project identity");
}
return id;
}
export function verifyInventory(rows, source = "repd") {
if (!Array.isArray(rows)) throw new TypeError(source + " inventory must be an array");
const refs = new Set();
for (const row of rows) {
const id = identity(row, source);
if (refs.has(id)) throw new Error("Duplicate " + source + " identity: " + id);
refs.add(id);
if (source === "repd" && row?.technology === "interconnector") {
throw new Error("Interconnector record inside REPD inventory: " + id);
}
}
return refs.size;
}
function technologyMatches(row, selection, source) {
return source === "interconnector" || selection.technology === "all" ||
row?.technology === selection.technology;
}
function matches(row, selection, source, except = "") {
if (except !== "technology" && !technologyMatches(row, selection, source)) return false;
for (const name of ["status", "operator", "region"]) {
if (name !== except && selection[name] !== "All" &&
label(row?.[name]) !== selection[name]) return false;
}
return true;
}
function mwScaled(value) {
if (value === null || value === undefined || value === "") return null;
const n = Number(value);
return Number.isFinite(n) && n >= 0 ? Math.round(n * DECIMAL_SCALE) : null;
}
function unit(row, source) {
const unitValue = typeof row?.capacity_unit === "string" && row.capacity_unit.trim();
if (unitValue) return unitValue;
if (source === "repd" && row?.technology === "solar") return "MWp";
return "MW";
}
function emptyTotals() {
return {
projects: 0,
missingCapacity: 0,
recordedByUnit: {},
solarMwp: 0,
otherMw: 0,
recordedMixed: 0,
};
}
function accumulate(totals, row, source) {
totals.projects++;
const mw = mwScaled(row?.capacity_mw);
if (mw === null) {
totals.missingCapacity++;
return;
}
const sourceUnit = unit(row, source);
totals.recordedByUnit[sourceUnit] = (totals.recordedByUnit[sourceUnit] ?? 0) + mw;
if (source === "repd" && row?.technology === "solar") totals.solarMwp += mw;
else totals.otherMw += mw;
totals.recordedMixed += mw; // Legacy comparison only: not comparable across MW/MWp.
}
function displayTotals(totals) {
const convert = value => Number((value / DECIMAL_SCALE).toFixed(6));
return {
projects: totals.projects,
missingCapacity: totals.missingCapacity,
recordedByUnit: Object.fromEntries(Object.entries(totals.recordedByUnit)
.map(([k, value]) => [k, convert(value)]).sort((a, b) => a[0].localeCompare(b[0], "en-GB"))),
solarMwp: convert(totals.solarMwp),
otherMw: convert(totals.otherMw),
recordedMixed: convert(totals.recordedMixed),
mixedUnitWarning: "Combined recorded MW/MWp is a database sum, not a physically comparable capacity or generation measure.",
};
}
function grouped(rows, dimension, source) {
const groups = new Map();
for (const project of rows) {
const key = dimension === "technology" && source === "interconnector"
? "Interconnector" : label(project?.[dimension]);
if (!groups.has(key)) groups.set(key, { label: key, totals: emptyTotals(), ids: [] });
const group = groups.get(key);
group.ids.push(identity(project, source));
accumulate(group.totals, project, source);
}
return [...groups.values()].map(group => ({
label: group.label,
...displayTotals(group.totals),
ids: group.ids,
})).sort((a, b) => b.recordedMixed - a.recordedMixed ||
b.projects - a.projects || a.label.localeCompare(b.label, "en-GB"));
}
function facets(rows, selection, source) {
const result = {};
for (const dimension of ["technology", "status", "operator", "region"]) {
const counts = new Map();
for (const row of rows) {
if (!matches(row, selection, source, dimension)) continue;
const option = dimension === "technology" && source === "interconnector"
? "interconnector" : label(row?.[dimension]);
counts.set(option, (counts.get(option) ?? 0) + 1);
}
result[dimension] = [...counts].map(([value, count]) => ({ value, count }))
.sort((a, b) => a.value.localeCompare(b.value, "en-GB"));
}
return result;
}
/**
* Return a single consistent selection for Operator/Status/Region/Technology reports.
* All filters intersect, no report button resets a prior cockpit selection.
* Interconnectors have their own namespace and never enter the 7,775 REPD total.
* Grid is reserved for a future verified source; it is NOT silently shown as zero.
*/
export function buildCockpitReport(repdRecords, {
dimension = "operator", filters = {}, interconnectors = null
} = {}) {
if (!REPORT_DIMENSIONS.includes(dimension)) {
throw new TypeError("Unsupported report dimension: " + dimension);
}
const selection = cockpitSelection(filters);
verifyInventory(repdRecords, "repd");
const source = selection.technology === "interconnector" ? "interconnector" :
selection.technology === "grid" ? "grid" : "repd";
if (source === "grid" || (source === "interconnector" && !Array.isArray(interconnectors))) {
return {
source, availability: SOURCE_UNAVAILABLE, selection, dimension,
sourceProjects: null, matchingProjects: null, groups: [], facets: {},
message: source === "grid"
? "Grid reporting requires a verified, separately identified asset inventory."
: "Interconnector inventory not supplied; never mixed into REPD.",
};
}
const universe = source === "interconnector" ? interconnectors : repdRecords;
if (source === "interconnector") verifyInventory(universe, source);
const rows = universe.filter(row => matches(row, selection, source));
const overall = emptyTotals();
for (const row of rows) accumulate(overall, row, source);
return {
source, availability: "AVAILABLE", dimension, selection,
sourceProjects: universe.length,
matchingProjects: rows.length,
totals: displayTotals(overall),
groups: grouped(rows, dimension, source),
facets: facets(universe, selection, source),
ids: rows.map(row => identity(row, source)),
rows, // Original references: retained for native REPD MAP/A4/project drillback.
};
}