GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world

Boq and 1 more file

A JavaScript module in the world folder of GlobalGrid2050 that converts to CSV (`toCsv`) and calculates planar distances (units: kV, mm²), covering cables and overhead lines (OHL).

521 lines of JavaScript from globalgrid2050, in 2 files. Topic: Solar and storage design. Section 132 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Boq render · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/boq.mjs lines 1–374
  2. Buffers transform · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/buffers.mjs lines 1–147

Boq

A JavaScript module in the world folder of GlobalGrid2050 that converts to CSV (`toCsv`) and calculates planar distances (units: kV, mm²), covering cables and overhead lines (OHL).

Set aside from the main view: 93% of its lines are the same as solar-design-studio/202609271740-site-world/world/boq.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with Boq; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9311 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/boq.mjs:1-391 144f838f33337d17748f71fb4d8e01bf8363092d
  • sha256 879f45f5c60c529feda65641d15ce6f43dc6d3bdf75ef8bb9888e4e6c1a46cd4
  • target sha256 8a5c9d55b785e661985e9f932977f57a804313e3865e2dedf2a6aeceddb70027
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/boq.mjs · lines 1–374 of 374 · version 2026-09-27 01:45 · Not reached from any entry point (candidate for review) · pattern armouredOf (shared by 2 files)

What it does
It lists and searches cables and overhead lines (OHL). Defines 22 functions or classes, including num, fmt, planLength, bendCount, lengthOf. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'boq'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables, overhead lines (OHL).
Downstream impact
Used directly by 1 file: Design Earthworks (globalgrid2050).
What it achieves
It is built from the num step (`num`), the fmt step (`fmt`) and the plan length helper (`planLength`). A bill of quantities from a design document.
Why it matters
Imported by Design Earthworks.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
Boq Assumptions (import)
Used by
imported by Design Earthworks (import), mentioned in Standalone (comment link)
Produces
STATUSES, buildBoq, toCsv
Defines here
num, fmt, planLength, bendCount, lengthOf, weakest, armouredOf, cableRows, trenchRows, roadRows, padRows, fenceRows, hddRows, pileRows, ohlRows, n, rateOf, buildBoq, skip, add, cell, toCsv
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270145-site-world-v3/world/boq.mjs:1-374 · blob 8e370420fbc2d1b7a3b7f4f8a98a992cc828f89b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: unreached_review
// boq.mjs: a bill of quantities from a design document.
//
// buildBoq(doc, { sections, cables, rates, currency }) -> { rows, skipped, total }
//   doc       { items: [{ id, kind, ...parameters, results }] }, kind one of
//             cable, trench, road, pad, fence, hdd, piles. `results` holds what
//             the design tools computed: routeCable / cableSummary for a cable,
//             trenchSummary for a trench, cutFillForPlatform for a pad, and
//             { length2d, length3d, area } style numbers for the rest.
//   sections  parsed web/world/data/trench-sections.json (needed for trenches)
//   cables    parsed web/world/data/cables.json (optional, resolves cableId)
// A cable is billed on its identity: cableId, or else voltageKv + csaMm2 + conductor + armoured all given.
// A cable with neither is skipped with a reason, never summed into an assumed row. A cable item may carry
// trench: { sectionId, results } for the trench cut for it; that trench is billed as a trench item.
//   rates     optional { [code]: number | { rate, unit } } supplied by the user.
//             With no rates, no money appears anywhere in the output.
//
// Every row: { code, description, unit, quantity, status, basis, sources }.
// status is one of
//   computed   measured from design geometry and values the design supplied
//   estimated  derived from design results by a stated simplification
//   assumed    rests on a default from boq-assumptions.mjs the design did not set
// Rows with the same code are summed; the merged status is the weakest one.
//
// toCsv(boq) -> CSV text: the disclaimer line, then the column header. Pure: no DOM, no fetch.

import { CABLE_DEFAULTS, CABLE_ALLOWANCES, ROAD_BUILD_UPS, FENCE_DEFAULTS, BEDDING_DEFAULTS, BASIS, DISCLAIMER } from './boq-assumptions.mjs';

const GROUND = `ground ${BASIS.ground}, levels in ${BASIS.datum}`;

export const STATUSES = ['computed', 'estimated', 'assumed'];
const RANK = { computed: 0, estimated: 1, assumed: 2 };
const num = (v) => (v != null && v !== '' && Number.isFinite(Number(v)) ? Number(v) : null);
const fmt = (x, dp = 2) => Number(x.toFixed(dp)).toString();

function planLength(path) {
  let s = 0;
  for (let k = 1; k < (path || []).length; k++) s += Math.hypot(path[k][0] - path[k - 1][0], path[k][1] - path[k - 1][1]);
  return s;
}

function bendCount(path) {
  let n = 0;
  for (let i = 1; i < (path || []).length - 1; i++) {
    const [a, b, c] = [path[i - 1], path[i], path[i + 1]];
    const cr = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]);
    const dot = (b[0] - a[0]) * (c[0] - b[0]) + (b[1] - a[1]) * (c[1] - b[1]);
    if (Math.abs(Math.atan2(cr, dot)) > 1e-6) n++;
  }
  return n;
}

// Best length an item offers: true 3D first, then plan, then its own path.
function lengthOf(item) {
  const r = item.results || {};
  const l3 = num(r.length3d) ?? num(r.boreLength);
  if (l3 != null) return { value: l3, status: 'computed', basis: 'true 3D length from design results' };
  const l = num(r.length);
  if (l != null) return { value: l, status: 'computed', basis: 'length from design results' };
  const l2 = num(r.length2d);
  if (l2 != null) return { value: l2, status: 'estimated', basis: 'plan length; no ground model, slope not included' };
  if (Array.isArray(item.path) && item.path.length > 1) {
    return { value: planLength(item.path), status: 'estimated', basis: 'plan length of the drawn path; slope not included' };
  }
  return null;
}

const weakest = (...s) => s.reduce((a, b) => (RANK[b] > RANK[a] ? b : a), 'computed');

// ---------------------------------------------------------------- by kind

const armouredOf = (id) => /armour/i.test(id || '') && !/unarmour/i.test(id || '');

function cableRows(item, ctx, add, skip) {
  if (item.trench) trenchRows({ id: `${item.id ?? 'cable'}-trench`, kind: 'trench', ...item.trench }, ctx, add, skip);
  let { voltageKv, csaMm2, conductor, armoured } = item;
  let code, name;
  if (item.cableId) {
    const c = ctx.cables ? (ctx.cables.cables || []).find((k) => k.id === item.cableId) : null;
    if (ctx.cables && !c) return skip(item, `unknown cableId ${item.cableId}`);
    if (c) { voltageKv ??= c.voltage_kv; csaMm2 ??= c.csa_mm2; conductor ??= c.conductor; }
    armoured ??= armouredOf(item.cableId);
    code = `CAB-${item.cableId}`;
    name = item.cableId;
  } else {
    if (voltageKv == null || csaMm2 == null || !conductor || typeof armoured !== 'boolean') {
      return skip(item, 'no cable identity: give cableId, or voltageKv, csaMm2, conductor and armoured');
    }
    code = `CAB-${voltageKv}KV-${conductor}-${csaMm2}-${armoured ? 'ARM' : 'UNARM'}`.toUpperCase();
    name = code.slice(4);
  }
  const r = item.results || {};
  const circuits = num(item.circuits) ?? 1;
  const cores = Array.isArray(r.cores) && r.cores.every((c) => num(c.length3d) != null) ? r.cores : null;
  const perCircuit = num(item.coresPerCircuit) ?? (cores ? cores.length : null);
  const nCores = perCircuit ?? CABLE_DEFAULTS.coresPerCircuit;
  const coreNote = perCircuit != null ? `${nCores} cores per circuit` : `${nCores} cores per circuit (assumed)`;
  let laid, status, basis;
  if (cores && perCircuit === cores.length) {
    laid = cores.reduce((s, c) => s + c.length3d, 0) * circuits;
    status = 'computed';
    basis = `sum of true 3D core axis lengths x ${circuits} circuit(s)`;
  } else {
    const L = lengthOf(item);
    if (!L) return skip(item, 'no route length in results');
    laid = L.value * nCores * circuits;
    status = weakest(L.status, perCircuit != null ? 'computed' : 'assumed');
    basis = `${L.basis} x ${coreNote} x ${circuits} circuit(s)`;
  }
  const kv = voltageKv != null ? `${voltageKv} kV` : 'voltage not given';
  const size = csaMm2 != null ? `${csaMm2} mm²` : 'size not given';
  const kind = `${kv} ${conductor || 'conductor not given'} ${size} ${armoured ? 'armoured' : 'unarmoured'} (${name})`;
  add({ code, description: `Cable ${kind}, laid length`, unit: 'm', quantity: laid, status, basis, rateKey: code }, item);

  const a = item.allowances || {};
  const slackPct = num(a.slackPct) ?? CABLE_DEFAULTS.slackPct;
  const { snakingPct: S, terminationM: T } = CABLE_ALLOWANCES;
  const termM = num(a.terminationM) ?? CABLE_DEFAULTS.terminationM;
  const given = num(a.slackPct) != null && num(a.terminationM) != null;
  const allowance = laid * slackPct / 100 + termM * 2 * nCores * circuits;
  add({
    code: `${code}-ALLOW`, description: `Cable ${kind}, allowances`, unit: 'm', quantity: allowance,
    status: given ? status : 'assumed', rateKey: code,
    basis: `slack ${slackPct} % of laid length${num(a.slackPct) != null ? '' : ` (assumed ${S.unit})`} + ${termM} m tail per core per end`
      + `${num(a.terminationM) != null ? '' : ' (assumed)'}; same allowances as the drum schedule`,
  }, item);
}

function trenchRows(item, ctx, add, skip) {
  const sec = (ctx.sections?.sections || []).find((s) => s.id === item.sectionId);
  if (!sec) return skip(item, item.sectionId ? `unknown sectionId ${item.sectionId}` : 'no sectionId');
  const r = item.results || {};
  const L = lengthOf(item);
  if (!L) return skip(item, 'no trench length in results');
  const width = num(r.width) ?? sec.trench_width_m;
  const depth = num(r.depth) ?? sec.trench_depth_m;
  const tag = `TR-${sec.id}`;
  add({ code: `${tag}-LEN`, description: `Trench ${sec.id} (${sec.voltage_class}), length`, unit: 'm', quantity: L.value, status: L.status, basis: L.basis }, item);

  const spoil = num(r.spoil) ?? num(r.spoilVolumeM3);
  add(spoil != null
    ? { code: `${tag}-SPOIL`, description: `Trench ${sec.id}, excavated spoil (bank volume)`, unit: 'm³', quantity: spoil,
        status: 'computed',
        basis: `cut volume against the ground model (${GROUND}); ${BASIS.spoil}` }
    : { code: `${tag}-SPOIL`, description: `Trench ${sec.id}, excavated spoil (bank volume)`, unit: 'm³', quantity: L.value * width * depth,
        status: 'estimated',
        basis: `length x ${width} m wide x ${depth} m deep; vertical walls; ${BASIS.spoil}` }, item);

  const t = num(sec.bedding?.thickness_mm);
  if (t != null) {
    const trefoil = /trefoil/i.test(sec.formation || '');
    const unit = num(sec.duct_od_mm) ?? num(sec.phase_spacing_mm);
    const env = unit != null ? (trefoil ? unit * (1 + Math.sqrt(3) / 2) : unit) : BEDDING_DEFAULTS.envelopeMm;
    const envNote = unit != null ? `${fmt(env, 0)} mm ${trefoil ? 'trefoil' : 'single layer'} envelope` : `${env} mm envelope (assumed)`;
    add({
      code: `${tag}-BED`, description: `Trench ${sec.id}, bedding: ${sec.bedding.material}`, unit: 'm³',
      quantity: L.value * width * (2 * t + env) / 1000, status: unit != null ? 'estimated' : 'assumed',
      basis: `length x ${width} m x (${t} mm bed + ${envNote} + ${t} mm above); gross, cable and duct volume not deducted`,
    }, item);
  }
  const m = sec.marker?.type || '';
  if (m) {
    const count = /each/i.test(m) ? (num(sec.circuits) ?? 1) : 1;
    const tape = /tape/i.test(m);
    add({
      code: `${tag}-${tape ? 'TAPE' : 'TILE'}`, description: `Trench ${sec.id}, ${tape ? 'warning tape' : 'protection tile'}`,
      unit: 'm', quantity: L.value * count, status: L.status,
      basis: `trench length x ${count} run(s): ${m}`,
    }, item);
  }
}

function roadRows(item, ctx, add, skip) {
  const r = item.results || {};
  const custom = Array.isArray(item.buildUp) && item.buildUp.length ? item.buildUp : null;
  const surface = item.surface || 'unbound';
  const std = ROAD_BUILD_UPS[surface];
  if (!custom && !std) return skip(item, `unknown surface ${surface}; supply buildUp`);
  let area = num(r.area), aStatus = 'computed', aBasis = 'plan area from design results';
  if (area == null) {
    const L = lengthOf(item), w = num(item.widthM) ?? num(r.width);
    if (!L || w == null) return skip(item, 'no road area, or length and widthM');
    area = L.value * w; aStatus = L.status; aBasis = `${L.basis} x ${w} m wide`;
  }
  const tag = `RD-${surface.toUpperCase()}`;
  add({ code: `${tag}-AREA`, description: `Road, ${custom ? surface : std.label}, area`, unit: 'm²', quantity: area, status: aStatus, basis: aBasis }, item);
  const layers = custom || std.layers;
  layers.forEach((ly, i) => {
    const key = ly.key || `L${i + 1}`;
    const assumed = !custom || ly.assumed === true;
    add({
      code: `${tag}-${key}`, description: `Road, ${ly.material}`, unit: 'm³', quantity: area * ly.thicknessMm / 1000,
      status: assumed ? 'assumed' : aStatus,
      basis: `area x ${ly.thicknessMm} mm${assumed ? ' (assumed build-up, as road.mjs draws it)' : ' (design build-up)'}; compacted volume`,
    }, item);
  });
  const lvl = `formation under the finished road; ${GROUND}`;
  if (num(r.cutM3) != null) add({ code: `${tag}-CUT`, description: 'Road, cut to formation', unit: 'm³', quantity: num(r.cutM3),
    status: 'computed', basis: `cut against the ground model to the ${lvl}; ${BASIS.spoil}; batters at assumed slopes` }, item);
  if (num(r.fillM3) != null) add({ code: `${tag}-FILL`, description: 'Road, fill to formation', unit: 'm³', quantity: num(r.fillM3),
    status: 'computed', basis: `fill against the ground model to the ${lvl}; compacted, no shrinkage factor; batters at assumed slopes` }, item);
  if (!custom && std.geotextile) {
    add({ code: `${tag}-GEOTEX`, description: 'Road, separation geotextile', unit: 'm²', quantity: area, status: 'assumed', basis: 'area, no laps (assumed build-up)' }, item);
  }
}

function padRows(item, ctx, add, skip) {
  const r = item.results || {};
  const area = num(r.polygonArea) ?? num(r.area);
  if (area == null && num(r.cut) == null) return skip(item, 'no pad results');
  const tag = `PAD-${item.id}`;
  if (area != null) add({ code: `${tag}-AREA`, description: `Pad ${item.id}, plan area`, unit: 'm²', quantity: area, status: 'computed', basis: 'polygon area' }, item);
  const lvl = num(r.level) != null ? ` to level ${fmt(r.level, 3)} m above Ordnance Datum Newlyn` : '';
  if (num(r.cut) != null) add({ code: `${tag}-CUT`, description: `Pad ${item.id}, cut`, unit: 'm³', quantity: r.cut,
      status: 'computed',
      basis: `cut against the ground model${lvl} (${GROUND}); ${BASIS.spoil}` }, item);
  if (num(r.fill) != null) add({ code: `${tag}-FILL`, description: `Pad ${item.id}, fill`, unit: 'm³', quantity: r.fill,
      status: 'computed',
      basis: `fill against the ground model${lvl} (${GROUND}); compacted, no shrinkage factor` }, item);
  const th = num(item.thicknessM);
  if (th != null && area != null) {
    const mat = item.material || 'pad construction';
    // The thickness is a design choice the tools assume (pad.mjs stone depth); billed as assumed unless the
    // item says thicknessAssumed: false.
    const given = item.thicknessAssumed === false;
    add({ code: `${tag}-SLAB`, description: `Pad ${item.id}, ${mat}`, unit: 'm³', quantity: area * th, status: given ? 'computed' : 'assumed',
      basis: `area x ${th} m thick${given ? ' (design thickness)' : ' (assumed thickness)'}` }, item);
  }
}

function fenceRows(item, ctx, add, skip) {
  const L = lengthOf(item);
  if (!L) return skip(item, 'no fence length');
  const spacing = num(item.postSpacingM) ?? FENCE_DEFAULTS.postSpacingM;
  const runs = num(item.runs) ?? 1;
  const bends = num(item.results?.bends?.length) ?? bendCount(item.path);
  const tag = `FEN-${item.fenceType || 'STD'}`.toUpperCase();
  add({ code: `${tag}-LEN`, description: `Fence${item.fenceType ? ` ${item.fenceType}` : ''}, length`, unit: 'm', quantity: L.value, status: L.status, basis: L.basis }, item);
  // The fence tool's own counts win: they are what the readout shows (code review 4).
  const c = item.results?.counts;
  if (c && num(c.posts) != null) {
    add({ code: `${tag}-POST`, description: 'Fence, posts (all)', unit: 'nr', quantity: c.posts, status: 'computed',
      basis: `counted by the fence tool: ${num(c.cornerPosts) ?? 0} corner, ${num(c.gatePosts) ?? 0} gate` }, item);
    if (num(c.strainers)) add({ code: `${tag}-STRAIN`, description: 'Fence, straining posts', unit: 'nr', quantity: c.strainers, status: 'computed', basis: 'counted by the fence tool' }, item);
    if (num(c.struts)) add({ code: `${tag}-STRUT`, description: 'Fence, struts', unit: 'nr', quantity: c.struts, status: 'computed', basis: 'counted by the fence tool' }, item);
    const g = num(item.gates);
    if (g) add({ code: `${tag}-GATE`, description: 'Fence, gates', unit: 'nr', quantity: g, status: 'computed', basis: 'count from design' }, item);
    return;
  }
  const perRun = Math.ceil(L.value / runs / spacing - 1e-9) + 1;
  add({
    code: `${tag}-POST`, description: 'Fence, line posts', unit: 'nr', quantity: perRun * runs,
    status: num(item.postSpacingM) != null ? L.status : 'assumed',
    basis: `ceil(length / ${spacing} m) + 1 per run, ${runs} run(s)${num(item.postSpacingM) != null ? '' : ' (assumed spacing)'}`,
  }, item);
  add({
    code: `${tag}-STRAIN`, description: 'Fence, straining posts', unit: 'nr', quantity: 2 * runs + bends,
    status: 'assumed', basis: `one at each run end and each of ${bends} bend(s); counted among the line posts (assumed practice)`,
  }, item);
  const gates = num(item.gates);
  if (gates) add({ code: `${tag}-GATE`, description: 'Fence, gates', unit: 'nr', quantity: gates, status: 'computed', basis: 'count from design' }, item);
}

function hddRows(item, ctx, add, skip) {
  const L = lengthOf(item);
  if (!L) return skip(item, 'no bore length');
  add({ code: 'HDD-BORE', description: 'Horizontal directional drill, bore length', unit: 'm', quantity: L.value, status: L.status, basis: L.basis }, item);
  const ducts = num(item.ducts);
  if (ducts) {
    const od = num(item.ductOdMm);
    add({ code: `HDD-DUCT${od ? `-${od}` : ''}`, description: `HDD duct${od ? ` ${od} mm OD` : ''}`, unit: 'm', quantity: L.value * ducts,
        status: L.status,
        basis: `bore length x ${ducts} duct(s)` }, item);
  }
}

function pileRows(item, ctx, add, skip) {
  const r = item.results || {};
  const count = num(r.count) ?? num(item.count) ?? (Array.isArray(item.points) ? item.points.length : null);
  if (count == null) return skip(item, 'no pile count');
  const type = item.pileType || 'STD';
  add({ code: `PIL-${type}`.toUpperCase(), description: `Piles${item.pileType ? ` ${item.pileType}` : ''}, count`, unit: 'nr', quantity: count,
    status: 'computed', basis: 'count from design' }, item);
  const emb = num(r.totalEmbedmentM) ?? (num(item.embedmentM) != null ? count * item.embedmentM : null);
  if (emb != null) add({ code: `PIL-${type}-EMB`.toUpperCase(), description: 'Piles, total embedded length', unit: 'm', quantity: emb,
      status: 'computed',
      basis: num(r.totalEmbedmentM) != null ? 'sum from design results' : `count x ${item.embedmentM} m` }, item);
}

// Overhead line zone conflicts (ohl-zones.mjs), one item per design item flagged: { id, kind: 'ohlZone', zone, height,
// goalposts } counts. Listed so the bill carries them; illustrative, on assumed tower heights and sag.
function ohlRows(item, ctx, add) {
  const basis = 'illustrative: tower heights and sag assumed; HSE GS6 paragraphs 11, 19 and 25';
  const n = k => num(item[k]) ?? 0;
  if (n('zone')) add({ code: 'OHL-ZONE', description: 'Overhead line zone conflicts: plan the work under GS6 with the network operator',
    unit: 'nr', quantity: n('zone'), status: 'estimated', basis }, item);
  if (n('height')) add({ code: 'OHL-HEIGHT', description: 'Working height reaches an overhead line exclusion distance (height user-set)',
    unit: 'nr', quantity: n('height'), status: 'estimated', basis }, item);
  if (n('goalposts')) add({ code: 'OHL-GOAL', description: 'Goalpost crossing points under overhead lines, suggested (HSE GS6 paragraphs 21 and 22)',
    unit: 'nr', quantity: n('goalposts'), status: 'estimated', basis }, item);
}

const KINDS = { cable: cableRows, trench: trenchRows, road: roadRows, pad: padRows, fence: fenceRows, hdd: hddRows, piles: pileRows,
  ohlZone: ohlRows };

// ---------------------------------------------------------------- build

function rateOf(rates, code, unit) {
  if (!rates || !(code in rates)) return null;
  const v = rates[code];
  const rate = typeof v === 'object' && v !== null ? num(v.rate) : num(v);
  if (rate == null) throw new Error(`boq: rate for ${code} is not a number`);
  if (typeof v === 'object' && v.unit && v.unit !== unit) throw new Error(`boq: rate for ${code} is per ${v.unit}, row is in ${unit}`);
  return rate;
}

export function buildBoq(doc, { sections = null, cables = null, rates = null, currency = null } = {}) {
  if (!doc || !Array.isArray(doc.items)) throw new Error('buildBoq: doc.items must be an array');
  const byCode = new Map(), skipped = [];
  const skip = (item, reason) => skipped.push({ id: item.id ?? null, kind: item.kind ?? null, reason });
  const add = (row, item) => {
    const prev = byCode.get(row.code);
    const id = item.id ?? `(${item.kind})`;
    if (!prev) { byCode.set(row.code, { ...row, rateKey: row.rateKey || row.code, sources: [id], bases: [row.basis] }); return; }
    if (prev.unit !== row.unit) throw new Error(`boq: ${row.code} mixes ${prev.unit} and ${row.unit}`);
    prev.quantity += row.quantity;
    prev.status = weakest(prev.status, row.status);
    if (!prev.sources.includes(id)) prev.sources.push(id);
    if (!prev.bases.includes(row.basis)) prev.bases.push(row.basis);
  };
  const ctx = { sections, cables };
  for (const item of doc.items) {
    const fn = KINDS[item?.kind];
    if (!fn) { skip(item || {}, `unknown kind ${item?.kind}`); continue; }
    fn(item, ctx, add, skip);
  }
  const rows = [...byCode.values()].map(({ bases, rateKey, ...r }) => {
    const row = { ...r, basis: bases.join('; ') };
    if (rates) {
      const rate = rateOf(rates, r.code, r.unit) ?? rateOf(rates, rateKey, r.unit);
      row.rate = rate;
      row.amount = rate == null ? null : rate * r.quantity;
    }
    return row;
  });
  const out = { rows, skipped };
  if (rates) {
    out.currency = currency;
    out.total = rows.reduce((s, r) => s + (r.amount ?? 0), 0);
    out.unrated = rows.filter((r) => r.rate == null).map((r) => r.code);
  }
  return out;
}

// ---------------------------------------------------------------- CSV

const DP = { m: 1, 'm²': 1, 'm³': 2, nr: 0 };
const cell = (v) => {
  const s = v == null ? '' : String(v);
  return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};

export function toCsv(boq) {
  const priced = 'total' in boq;
  const head = ['code', 'description', 'unit', 'quantity', 'status', 'basis', 'sources'];
  if (priced) head.push(`rate${boq.currency ? ` (${boq.currency})` : ''}`, `amount${boq.currency ? ` (${boq.currency})` : ''}`);
  const lines = [cell(DISCLAIMER), head.map(cell).join(',')];
  for (const r of boq.rows) {
    const line = [r.code, r.description, r.unit, (r.quantity).toFixed(DP[r.unit] ?? 2), r.status, r.basis, r.sources.join(' ')];
    if (priced) line.push(r.rate == null ? 'no rate' : r.rate, r.amount == null ? '' : r.amount.toFixed(2));
    lines.push(line.map(cell).join(','));
  }
  if (priced) lines.push(['TOTAL', 'Total of rated rows only', '', '', '', '', '', '', boq.total.toFixed(2)].map(cell).join(','));
  return lines.join('\r\n') + '\r\n';
}

Buffers

A JavaScript module in the world folder of GlobalGrid2050 that works with 33kV, 132kV, 66kV and 275kV, using BS5837 and BS 5837.

transformglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/buffers.mjs · lines 1–147 of 147 · version 2026-09-27 01:45 · Not reached from any entry point (candidate for review) · pattern voltageClass (shared by 6 files)

What it does
It calculates 33kV, 132kV, 66kV and 275kV. Defines 13 functions or classes, including voltageClass, part, sum, overheadRule, waterRule.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 33kV, 132kV, 66kV, 275kV, 400kV.
Inputs & outputs
Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV.
Downstream impact
Used directly by 2 files: Buffers UI (globalgrid2050); Buffers UI (globalgrid2050).
What it achieves
It builds zones (`buildZones`) and is built from the voltage class helper (`voltageClass`) and the part step (`part`). Offset zones around features in the world data, and a clash check for drawn items. Its code works with 33 kV, 132 kV and 275 kV.
Why it matters
Imported by Buffers UI.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
Offset (import), Clash (import)
Used by
imported by Buffers UI (import), imported by Buffers UI (import), mentioned in Standalone (comment link)
Produces
SOURCES, OVERHEAD, GS6_BARRIER, WATER, ROAD_SETBACK, ROAD_WIDTH, RPA, DEFAULT_STEM_MM, voltageClass, overheadRule, waterRule, roadRule
Defines here
voltageClass, part, sum, overheadRule, waterRule, roadRule, stemDiameterMm, rootRule, drawnRule, ptsOf, buildZones, add, line
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270145-site-world-v3/world/buffers.mjs:1-147 · blob d5ee0c3a4aa0686a5b328c229356ae5c5e373935 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Buffers: offset zones around features in the world data, and a clash check for drawn items.
// Pure: no DOM. Every distance carries its source and a kind:
//   statutory  set by law or regulation (often a permit trigger rather than a ban; the note says which)
//   guidance   a published standard or regulator's guidance, followed in practice and often made binding by conditions
//   typical    common practice with no single rule; confirm with the authority named in the note
//   assumed    a value this tool supplies where the data has none (a width, a stem size); replace it when known
// A zone's distance is measured from the feature's line or outline in the data; parts[] break it into cited pieces.
// England and Wales rules. Scotland and Northern Ireland have their own regimes: check before relying on these.

import { offset, cleanPath } from './offset.mjs';

export const SOURCES = {
  GS6: 'HSE Guidance Note GS6 (fourth edition, 2013), Avoiding danger from overhead power lines: barriers 6 m horizontally from '
    + 'the nearest wire (paragraph 19); risks to manage within 10 m (paragraph 11), used here for steel-tower lines',
  ESQCR: 'Electricity Safety, Quality and Continuity Regulations 2002 (SI 2002/2665), regulation 17 and Schedule 2: minimum '
    + 'height of overhead conductors above ground; clearances applied as in ENA Technical Specification 43-8, Overhead line clearances',
  EPR: 'Environmental Permitting (England and Wales) Regulations 2016, Schedule 25 (flood risk activities); GOV.UK guidance '
    + '"Flood risk activities: environmental permits": a permit is needed for work within 8 m of the bank of a main river, 16 m if tidal',
  EA_BYELAWS: 'Environment Agency regional land drainage byelaws: consent for works near a main river, commonly within 8 m; the '
    + 'distance varies by region',
  IDB: 'Internal drainage board byelaws (model land drainage byelaws): consent needed within 9 m of a board-maintained watercourse; '
    + 'the distance varies by board',
  BS5837: 'BS 5837:2012 Trees in relation to design, demolition and construction, clause 4.6: root protection area radius '
    + '12 x stem diameter measured at 1.5 m above ground, capped at 707 m2 (15 m radius)',
  ROAD: 'No single national setback. The highway boundary and any building or improvement line are set by the local highway authority',
  ASSUMED: 'Assumed by this tool where the data gives no value; replace with a measured or surveyed figure',
  USER: 'Set by the designer on the drawn item'
};

// Overhead lines. Half-spread: centreline to outermost conductor at rest (ASSUMED typical cross-arm geometry,
// not measured). Support: wood poles for 33 kV and below, steel towers above (ASSUMED; some 66 and 132 kV lines
// are on wood poles, so a line may say support: 'pole' | 'tower'). Heights: statutory minimum above ground.
export const OVERHEAD = {
  '33kV': { halfSpread: 1.0, support: 'pole', minHeight: 5.2 },
  '66kV': { halfSpread: 2.5, support: 'tower', minHeight: 6.0 },
  '132kV': { halfSpread: 4.0, support: 'tower', minHeight: 6.7 },
  '275kV': { halfSpread: 6.0, support: 'tower', minHeight: 7.0 },
  '400kV': { halfSpread: 6.5, support: 'tower', minHeight: 7.3 }
};
export const GS6_BARRIER = { pole: 6, tower: 10 };
export const WATER = { main: 8, tidal: 16, idb: 9, halfWidth: 1 }; // halfWidth: ASSUMED centreline to bank
export const ROAD_SETBACK = 3;                                     // TYPICAL, from the carriageway edge
export const ROAD_WIDTH = { motorway: 11, A: 7.3, B: 6.5, minor: 5.5, local: 4.8, track: 3 }; // ASSUMED, as the ways layer
export const RPA = { perMm: 0.012, cap: 15 };                        // 12 x stem diameter; 707 m2 cap = 15 m radius
export const DEFAULT_STEM_MM = { tree: 300, hedge: 200 };             // ASSUMED where the data gives no stem

// Nominal kV -> class. Bands: >= 345 is 400 kV, >= 220 is 275 kV, >= 100 is 132 kV, >= 50 is 66 kV, else 33 kV.
export function voltageClass(kv) {
  const v = Number(kv);
  if (!(v > 0)) return '33kV';
  return v >= 345 ? '400kV' : v >= 220 ? '275kV' : v >= 100 ? '132kV' : v >= 50 ? '66kV' : '33kV';
}

const part = (what, m, kind, source) => ({ what, m, kind, source });
const sum = parts => parts.reduce((s, p) => s + p.m, 0);

// Pure: the rule for one overhead line -> { rule, kind, distance, parts, note }.
export function overheadRule(line) {
  const cls = voltageClass(line.voltage_kv), o = OVERHEAD[cls];
  const support = line.support === 'pole' || line.support === 'tower' ? line.support : o.support;
  const parts = [
    part('centreline to outermost conductor', o.halfSpread, 'assumed', SOURCES.ASSUMED),
    part(`barrier distance from the nearest wire (${support === 'pole' ? 'wood poles' : 'steel towers'})`, GS6_BARRIER[support], 'guidance', SOURCES.GS6)
  ];
  return { rule: `overhead-${cls}`, kind: 'guidance', distance: sum(parts), parts,
    note: `${cls} line. No work, storage or plant within the zone without the network operator's agreement. Conductors must stay `
      + `at least ${o.minHeight} m above ground (statutory: ${SOURCES.ESQCR}). Conductor swing in wind is not included.` };
}

// Pure: the rule for one watercourse. main: true | false | undefined (unknown), tidal, idb, width_m.
export function waterRule(w) {
  const half = w.width_m > 0 ? w.width_m / 2 : WATER.halfWidth;
  const halfPart = part('centreline to bank', half, w.width_m > 0 ? 'typical' : 'assumed', w.width_m > 0 ? 'Width from the data' : SOURCES.ASSUMED);
  if (w.main === false) {
    const parts = [halfPart, part('from the bank of a board-maintained watercourse', WATER.idb, 'typical', SOURCES.IDB)];
    return { rule: 'water-ordinary', kind: 'typical', distance: sum(parts), parts,
      note: 'Ordinary watercourse. Consent from the drainage board or lead local flood authority applies where it has byelaws.' };
  }
  const tidal = !!w.tidal, m = tidal ? WATER.tidal : WATER.main;
  const parts = [halfPart, part(`from the bank of a ${tidal ? 'tidal ' : ''}main river`, m, 'statutory', SOURCES.EPR)];
  return { rule: tidal ? 'water-main-tidal' : 'water-main', kind: 'statutory', distance: sum(parts), parts,
    note: (w.main === true ? 'Main river. ' : 'Main river status not in the data: treated as a main river until the Environment Agency '
      + 'main rivers map says otherwise. ') + `A permit trigger, not a ban. Byelaws may also apply: ${SOURCES.EA_BYELAWS}.` };
}

// Pure: the rule for one road (class and width_m as in the ways files).
export function roadRule(r) {
  const w = r.width_m > 0 ? r.width_m : ROAD_WIDTH[r.class] || ROAD_WIDTH.local;
  const parts = [part('centreline to carriageway edge', w / 2, r.width_m > 0 ? 'typical' : 'assumed', r.width_m > 0 ? 'Width from the data' : SOURCES.ASSUMED),
    part('setback from the carriageway edge', ROAD_SETBACK, 'typical', SOURCES.ROAD)];
  return { rule: 'road-setback', kind: 'typical', distance: sum(parts), parts, note: `${r.class || 'Road'}: a typical setback only. ${SOURCES.ROAD}.` };
}

// Pure: BS 5837 stem diameter for one or several stems (mm). Two to five stems combine as sqrt(sum of squares).
export function stemDiameterMm(t, fallback) {
  const s = Array.isArray(t.stems_mm) ? t.stems_mm.filter(v => v > 0) : t.stem_mm > 0 ? [t.stem_mm] : [];
  if (!s.length) return { mm: fallback, assumed: true };
  return { mm: s.length === 1 ? s[0] : Math.sqrt(s.reduce((a, v) => a + v * v, 0)), assumed: false, stems: s.length };
}

// Pure: root protection area rule for a tree or hedge.
export function rootRule(t, what) {
  const st = stemDiameterMm(t, DEFAULT_STEM_MM[what]);
  const r = Math.min(RPA.cap, st.mm * RPA.perMm);
  const parts = [part(`root protection radius (stem ${Math.round(st.mm)} mm${st.assumed ? ', assumed' : ''})`, r, st.assumed ? 'assumed' : 'guidance',
    st.assumed ? `${SOURCES.BS5837}. Stem size: ${SOURCES.ASSUMED}` : SOURCES.BS5837)];
  const note = (st.stems > 5 ? 'More than five stems: BS 5837 uses a different combination; check the survey. ' : '')
    + (what === 'hedge' ? 'Measured from the hedge line. ' : '') + 'A tree survey to BS 5837 replaces these figures.';
  return { rule: what === 'hedge' ? 'hedge-rpa' : 'tree-rpa', kind: st.assumed ? 'assumed' : 'guidance', distance: sum(parts), parts, note };
}

// Pure: the rule for a drawn item that carries its own buffer_m.
export function drawnRule(item) {
  const parts = [part(`clearance around the drawn ${item.kind || 'item'}`, +item.buffer_m, 'typical', SOURCES.USER)];
  return { rule: 'drawn-clearance', kind: 'typical', distance: sum(parts), parts, note: 'A clearance chosen by the designer.' };
}

const ptsOf = f => f.points || f.pts || (f.at ? [f.at] : Number.isFinite(f.x) ? [[f.x, f.y]] : Number.isFinite(f.e) ? [[f.e, f.n]] : []);
const AREA_KINDS = new Set(['pad', 'table']);

// Pure: zones for the world. world: { overhead, water, roads, trees, hedges, drawn } lists (any may be missing).
// origin { e, n }: subtracted from every point, so national-grid data becomes local metres (drawn items are
// already local and are never shifted). Returns [{ id, layer, feature, rule, kind, distance, parts, note, geometry, rings }].
export function buildZones(world = {}, { origin = null, segments } = {}) {
  const zones = [], shift = (pts, local) => (origin && !local ? pts.map(p => [p[0] - origin.e, p[1] - origin.n]) : pts.map(p => [p[0], p[1]]));
  const add = (layer, list, ruleFor, shape) => (Array.isArray(list) ? list : []).forEach((f, i) => {
    if (!f) return;
    const r = ruleFor(f);
    if (!r || !(r.distance > 0)) return;
    const pts = cleanPath(shift(ptsOf(f), layer === 'drawn'), shape(f).closed);
    if (!pts.length) return;
    const geometry = { pts, ...shape(f) };
    const { rings } = offset(pts, r.distance, { ...geometry, segments });
    zones.push({ id: `${layer}/${f.id ?? i}`, layer, feature: f.id ?? i, ...r, geometry, rings });
  });
  const line = () => ({ closed: false, area: false });
  add('overhead', world.overhead, overheadRule, line);
  add('water', world.water, waterRule, line);
  add('roads', world.roads, roadRule, line);
  add('trees', world.trees, t => rootRule(t, 'tree'), t => ({ closed: false, area: ptsOf(t).length > 2 }));
  add('hedges', world.hedges, h => rootRule(h, 'hedge'), line);
  add('drawn', world.drawn, d => (d.buffer_m > 0 ? drawnRule(d) : null), d => ({ closed: AREA_KINDS.has(d.kind), area: AREA_KINDS.has(d.kind) }));
  return zones;
}

export { offset };
export { checkClashes, itemGeometry, distToGeometry, geometryDistance, ITEM_WIDTH } from './clash.mjs';