Update noi

From atanasster/electionsbg · View interactive version

Update noi is an AI agent skill from the GitHub repository atanasster/electionsbg. Refresh the NOI (Национален осигурителен институт) social-security data behind /awarder/121082521 and the /pensions view. Three artifacts share this skill — the B1 per-fund cash-execution (ДОО 5500 / УчПФ 5591 / ГВРС 5592) → data/budget/noi/funds.json; the pension statistical yearbook ZIP → data/bud

How to use this skill

Skill file

Update NOI skill

<!-- pipeline-pointer:start (generated from the registry; edit scripts/pipeline/registry) -->

Pipeline: handler CODE0 runs this unattended — pnpm run pipeline:ingest --only update-noi. The registry holds its commands, gates and publish set; this runbook covers what a script cannot do (operator steps, judgement calls, troubleshooting). When a step fails, start from the repair packet the run writes, not from the procedure below.

<!-- pipeline-pointer:end -->

Refreshes the NOI per-fund cash-execution data that powers the "Социалноосигурителни фондове" drill-down on /budget. Single artifact: data/budget/noi/funds.json.

Three funds at the EBK level — all aggregated to fund 5500 from sub-funds:

| EBK code | Fund | What it covers | 2024 expenditure |

|---|---|---|---|

| 5500 | ДОО (Държавно обществено осигуряване) | Pensions, sickness/maternity, unemployment, labour-injury | €12.59B |

| 5591 | Учителски пенсионен фонд | Teacher pension top-up | €53M |

| 5592 | Фонд "Гарантирани вземания на работниците и служителите" | Bankruptcy receivables | €1M |

When to run

| Trigger | Action |

|---|---|

| Watcher: nssi_b1 describe-line says "N new B1 file(s)" or "N B1 file(s) re-uploaded" | tsx scripts/budget/noi/__write_funds.ts --fetch (auto-downloads + rebuilds funds.json) |

| User asks to refresh NOI / social-security data | Same |

| Adding a new fiscal year (e.g. 2026 once Jan 2027 file lands) | Same — TRY_YEARS in __write_funds.ts runs 2020 → the current year, so a new year needs no edit |

| Fresh clone, data/budget/noi/funds.json missing | --fetch re-run (the Referer workaround pulls the bodies) |

| Watcher: nssi_yearbook says "N new yearbook ZIP(s)" | Pensions ingest (§ Yearbook below) → pensions.json |

| Watcher: kfn_pensions says "N new КФН statistics period(s)" | КФН ingest (§ КФН below) → kfn/funds.json |

| Fresh clone, data/budget/noi/pensions.json or data/budget/kfn/funds.json missing | Run the yearbook / КФН ingests below (both auto-fetch cleanly) |

ЗБДОО per-fund plan (hand-keyed, no watcher)

data/budget/noi/fund_plan.json is the LAW side beside the B1 execution — чл. 1–8

of the annual Закон за бюджета на държавното обществено осигуряване. It has **no

fetch and no watcher of its own**: the figures are a table in Държавен вестник,

published once a year, so nothing will prompt you to add FY2027. The signal is the

dv_laws watcher reporting a ЗБДОО promulgation — the same flip that triggers

re-verifying the statutory constants in src/lib/bgTax.ts.

To add a year: append a YEARS entry in scripts/budget/noi/__write_fund_plan.ts

keyed from чл. 1–8, then:

pnpm exec tsx scripts/budget/noi/__write_fund_plan.ts
pnpm exec tsx scripts/budget/noi/__smoke_fund_plan.ts
pnpm run bucket:sync:paths budget

The sync is not optional — data/budget is bucket-served in production via

dataUrl(), so a committed fund_plan.json reaches localhost only.

Two invariants the smoke enforces, and the reason they exist. The чл. 1

headline is a gross sum of the fund lines, not a consolidated total: the parts

add to it exactly, which is only possible if no inter-fund transfer was

eliminated. So (1) never label it „консолидиран", and (2) never put it in variance

against funds.json, which IS consolidated — that comparison renders an

accounting-basis difference as execution. The „НОИ" line (~43% of the sum;

administration + non-fund payments) is marked isPeerFund: false so it is not

drawn beside the real funds, where it would be the largest entry.

Procedure

1. Fetch + rebuild (one command)

tsx scripts/budget/noi/__write_funds.ts --fetch

--fetch downloads the full-year (_12_) B1 for every year × fund via

scripts/budget/noi/fetch_b1.ts before parsing. nssi.bg 302-redirects B1 GETs

to its homepage for most clients, but sending a Referer of the

отчети-и-баланси listing page defeats the redirect and serves the real BIFF8

body; the fetcher validates the OLE2 magic bytes so an HTML redirect is never

cached, and overwrites a cached file only when the bytes differ (reports

saved / unchanged). Years whose _12_ file isn't published yet (the current

year mid-cycle — e.g. 2025 only had months 01–11 as of Jul 2026) simply 302 and

are skipped. Files land in raw_data/budget/noi/.

Then the writer iterates TRY_YEARS (2020 → the current year), skipping any year × fund

without a cached XLS, and writes data/budget/noi/funds.json (~16 KB).

Offline / testing: drop the --fetch flag to parse whatever is already cached.

To verify a cached file by hand: file raw_data/budget/noi/B1_2024_12_5500.xls

→ expect Composite Document File V2 Document … (an HTML document means a

stale manual download hit the redirect — re-run with --fetch).

Output sample:

  • 2024/5500: rev €6590528454M, exp €12585M
  • 2024/5591: rev €68700085M, exp €53M
  • 2024/5592: rev €1388894M, exp €1M
  →  wrote /Users/.../data/budget/noi/funds.json (1 year(s))

2. Sanity-check the output

Quick canary: the 2024 ДОО pensions figure (§4100) should be in the €11.0-€11.2B band. Anything below €5B or above €15B → re-check the source file or parser.

python3 -c "
import json
d = json.load(open('data/budget/noi/funds.json'))
for y in d['years']:
  print(y['fiscalYear'], 'pensions €', y['totals']['pensions']['amountEur'] // 1_000_000, 'M')
"

3. Stamp the ingest marker

tsx scripts/stamp-ingest.ts update-noi --summary "noi: 2024 (all 3 funds)"

Yearbook → pensions.json (the /pensions view)

Separate artifact from funds.json. The НОИ pension statistical yearbook drives

the per-oblast average pension, the pension size distribution, the cash-vs-bank

split, and the national wage/income/pension series. Unlike the B1 files, the

yearbook ZIP GETs cleanly — no manual-download dance.

# Fetch the newest editions (clean XLSX exists 2022+; 2021/2025-style unpublished
# years return an HTML 404 at HTTP 200 — the parser sniffs the PK magic bytes and
# skips them). Anchor: the watcher's describe-line names the new year.
for y in 2022 2023 2024; do
  curl -sSL -o raw_data/budget/noi/yearbooks/Yearbook_Pensions_${y}.zip \
    "https://www.nssi.bg/wp-content/uploads/Yearbook_Pensions_${y}.zip"
done

tsx scripts/budget/noi/__write_pensions.ts   # → data/budget/noi/pensions.json

Sanity: the run prints N oblasts, N brackets (Σ=<total>) per year — the bracket

sum MUST equal the "Общо" pensioner headline or the parser throws (§ the sum gate

in parse_yearbook_xlsx.ts). The Eurostat poverty line is fetched inline; it

degrades to null offline. Then git add data/budget/noi/pensions.json and

bucket:sync data/budget/noi/.

Pensioners by ТП → pensioners_by_tp.json (the 28-ТП map input)

pnpm run noi:pensioners-by-tp

data.egov.bg dataset 10480 („Брой на пенсионерите по териториални поделения на НОИ

(средномесечен брой) - по години"), one resource, updated about once a year (the 2025

column landed 2026-06-24). No watcher yet — run it with the yearbook. The ТП ↔ oblast

crosswalk is an explicit table in scripts/budget/noi/pensioners_by_tp.ts, checked against

each published name; a renamed or missing ТП THROWS, and every year's ТП rows must sum to

the published „Общо" or it throws. София-град (ТП 21) is SOFIA_CITY and София-област

(ТП 22) is SFO — never fold them. ТП 29 „Международни спогодби/договори" has no

territory and is kept as its own series, never placed on a map. Nothing renders it yet.

Then git add data/budget/noi/pensioners_by_tp.json and bucket:sync data/budget/noi/.

КФН → kfn/funds.json (private pillars 2 & 3)

The /pensions private-funds tile. КФН publishes a quarterly ZIP of English

workbooks. The URL is unpredictable (upload-dir + suffix) — the kfn_pensions

watcher fingerprints the fsc.bg/.../statistics/YYYY-N/ sub-page list; when a new

period appears, open that sub-page and grab its statistics_*.zip.

# Download the newest quarter's ZIP (from the sub-page the watcher named), then:
curl -sSL -o raw_data/budget/kfn/statistics_2025_q2.zip "<the ZIP URL>"
tsx scripts/budget/kfn/__write_funds.ts       # → data/budget/kfn/funds.json

**The writer MERGES; it does not overwrite.** `data/budget/kfn/funds.json` retains every quarter
ever ingested (`{latestPeriod, periods[]}`) and is the DURABLE store for that series —
`raw_data/budget/` is gitignored, so a history re-derived from the ZIPs on disk would be a
property of one machine and a fresh clone would silently restart from one quarter. Re-running the
same quarter is a no-op (byte-identical file); a corrected re-ingest replaces that quarter's rows.
It refuses to write a file with fewer periods than it read unless `--allow-shrink` is passed, since
a merge can only add or replace. `--zip <name>` targets one archive explicitly, which is how a
back-catalogue is seeded one quarter at a time.

It REFUSES a quarter missing a pillar. That is a parse failure, not a source gap, and it has
happened: an English archive ships both `VPF_*` (the voluntary pillar) and `DPF_*` (a
deferred-payment workbook with no Table №1-V), so a matcher that reached `DPF_*` first dropped the
whole pillar — 21 funds instead of 31, €851M of assets and 627,640 insured — and the shortfall then
reads as GROWTH against the neighbouring quarter. The runbook's own sanity line is
`[UPF:10 PPF:10 VPF:10 VPFOS:1]`; anything else is a bug.

**DEPLOY ORDER: code first, then data.** The served file changed shape (single period →
`{latestPeriod, periods[]}`). An old bundle against the new JSON iterates `data.funds` on
`undefined` and, since there is no ErrorBoundary in `src/`, blanks the whole of `/pensions`. The
reverse order degrades cleanly — a new bundle against the old JSON just self-suppresses the tile.
So `pnpm run deploy` BEFORE `bucket:sync`, not after.

**Joining a fund across quarters** — use `pillar` + `companyEn`, never `fundName`. The register
writes the fund name in the archive's own language (`UPF "DOVERIE"` vs `УПФ "ДОВЕРИЕ"`), so
`fundName` joins 0 of 21 rows across a BG/EN boundary.

Only the four accumulation workbooks (UPF/PPF/VPF/VPFOS) are parsed; DPF/LPPF are

payout-phase with a different layout and skipped. Sanity: the run prints

N funds [UPF:10 PPF:10 VPF:10 VPFOS:1]. Then git add + `bucket:sync

data/budget/kfn/`.

Parser internals

scripts/budget/noi/parse_b1_xls.ts reads two sheets:

Amounts in B1 files are in whole leva (not thousands like the budget-law tables) — moneyFromLeva doesn't apply the ×1000 multiplier.

Adding a new fiscal year

When a new full-year-end file (B1_{YYYY+1}_12_5500.xls) lands:

  1. Manually download all three funds (5500, 5591, 5592) for the new YYYY.
  2. Re-run tsx scripts/budget/noi/__write_funds.ts (no code change needed — the writer iterates years 2020 → the current year and gracefully skips missing files).
  3. Stamp the marker. (TRY_YEARS follows the calendar — no edit for a new year.)

The watcher's nssi_b1.ts tracks the current and prior fiscal year — extend its trackedYears() function if you need monitoring of older years.

File map

| Path | Purpose |

|---|---|

| scripts/budget/noi/parse_b1_xls.ts | XLS reader + typed snapshot builder |

| scripts/budget/noi/__write_funds.ts | Writer CLI (this is what you run) |

| scripts/budget/noi/__smoke_b1.ts | One-fund inspection for debugging |

| raw_data/budget/noi/B1_*.xls | Manually-cached source XLS files (gitignored) |

| data/budget/noi/funds.json | The committed artifact |

| scripts/budget/noi/pensioners_by_tp.ts + fetch_pensioners_by_tp.ts | Pensioners by ТП + the ТП ↔ oblast crosswalk |

| data/budget/noi/pensioners_by_tp.json | Pensioners by ТП, 2010→ (no reader yet) |

| scripts/watch/sources/nssi_b1.ts | Daily fingerprint of B1 file signatures |

| src/data/budget/useBudget.tsx (useNoiFunds) | React Query hook the drilldown consumes |

| src/screens/components/budget/BudgetFlowSocialFundsDrilldown.tsx | The UI |

What this skill does NOT do

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.