All files / scripts/statskontoret/domain budget.ts

97.95% Statements 48/49
87.5% Branches 49/56
100% Functions 7/7
97.77% Lines 44/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218                                                                            15x 15x 24x 24x 24x 24x   23x 23x     24x       24x                         24x                         24x                 24x 24x   22x                 22x   24x 24x   24x                       15x                           1x 1x 2x 2x       2x   1x   1x                                 4x                       4x 8x 8x 8x 2x 2x 1x   1x   2x   6x                     4x 6x                       4x         2x 2x 1x      
/**
 * @module scripts/statskontoret/domain/budget
 * @description Budget-outturn row parsing and summary aggregation for the
 * årsutfall, månadsutfall and budget-time-series Statskontoret workbooks.
 *
 * Field names are normalised so Swedish characters and capitalisation
 * differences in Statskontoret's column headers are tolerated transparently.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import { rowsToRecords } from '../extractors/rows-to-records.js';
import {
  buildRecordLookup,
  findField,
  parseStatskontoretOptionalInt,
  parseStatskontoretSwedishNumber,
  roundOneDecimal,
} from '../internal/text.js';
import type {
  StatskontoretBudgetOptions,
  StatskontoretBudgetRow,
  StatskontoretBudgetSummary,
  StatskontoretWorkbook,
} from '../types.js';
 
/**
 * Parse budget-outturn records into typed `StatskontoretBudgetRow` rows.
 *
 * Covers both `arsutfall` (annual, no month) and `manadsutfall` (monthly) as
 * well as the `budget-time-series` XLSX series.  Field names are normalised so
 * Swedish characters and capitalisation differences are tolerated.
 */
export function parseBudgetRows(
  records: readonly Record<string, string>[],
  options: StatskontoretBudgetOptions = {},
): StatskontoretBudgetRow[] {
  const rows: StatskontoretBudgetRow[] = [];
  for (const record of records) {
    const lookup = buildRecordLookup(record);
    const yearRaw = findField(lookup, ['år', 'ar', 'year', 'kalenderår', 'kalenderar']);
    const year = parseStatskontoretOptionalInt(yearRaw ?? '') ?? options.fallbackYear;
    if (!year) continue;
 
    const monthRaw = findField(lookup, ['månad', 'manad', 'month', 'månadsperiod']);
    const month = parseStatskontoretOptionalInt(monthRaw ?? '') ?? options.fallbackMonth;
 
    const docType =
      options.documentType ??
      findField(lookup, ['dokumenttyp', 'dokumenttype', 'typ', 'inkomst_utgift', 'inkomstutgift']) ??
      '';
 
    const title =
      findField(lookup, [
        'inkomsttitelnamn',
        'inkomsttitelgruppsnamn',
        'anslagsnamn',
        'utgiftsomradesnamn',
        'utgiftsomrade',
        'titel',
        'name',
        'namn',
        'rubrik',
      ])?.trim() ?? '';
 
    const code = findField(lookup, [
      'inkomsttitel',
      'inkomsttitelnummer',
      'inkomsttitelnr',
      'anslagsnr',
      'anslagsnummer',
      'anslagspost',
      'utgiftsomradesnr',
      'kod',
      'code',
      'nummer',
    ])?.trim();
 
    const outturnRaw = findField(lookup, [
      'utfall',
      'outturn',
      'utfallmsek',
      'utfallbelopp',
      'inkomstutfall',
      'utgiftsutfall',
      'belopp',
    ]);
    const outturn = parseStatskontoretSwedishNumber(outturnRaw ?? '');
    if (outturn === undefined) continue;
 
    const budgetRaw = findField(lookup, [
      'budget',
      'budgetvarde',
      'budgetvärde',
      'anvisatbelopp',
      'anvisat',
      'statsbidrag',
      'ramanslag',
    ]);
    const budget = parseStatskontoretSwedishNumber(budgetRaw ?? '');
 
    const agency = findField(lookup, ['myndighet', 'myndighetsnamn', 'namn', 'authority'])?.trim();
    const status = findField(lookup, ['status', 'utfallsstatus', 'preliminar', 'preliminär'])?.trim();
 
    rows.push({
      year,
      ...(month !== undefined ? { month } : {}),
      documentType: docType,
      title,
      ...(code ? { code } : {}),
      outturn: roundOneDecimal(outturn),
      ...(budget !== undefined ? { budget: roundOneDecimal(budget) } : {}),
      ...(agency ? { agency } : {}),
      ...(status ? { status } : {}),
    });
  }
  return rows;
}
 
/**
 * Parse all sheets in a budget-outturn workbook and return a flat array of
 * typed rows sorted by year ascending, then month ascending (annual rows last
 * for the same year), then documentType alphabetically.  For single-type workbooks
 * (e.g. a file explicitly downloaded as "Inkomst"), pass
 * `options.documentType` to set the label uniformly.
 */
export function buildBudgetTimeSeries(
  workbook: StatskontoretWorkbook,
  options: StatskontoretBudgetOptions = {},
): StatskontoretBudgetRow[] {
  const rows: StatskontoretBudgetRow[] = [];
  for (const sheet of workbook.sheets) {
    const sheetDocType = options.documentType ?? inferDocTypeFromSheetName(sheet.name);
    const sheetOptions: StatskontoretBudgetOptions = {
      ...options,
      ...(sheetDocType ? { documentType: sheetDocType } : {}),
    };
    rows.push(...parseBudgetRows(rowsToRecords(sheet.rows), sheetOptions));
  }
  return rows.sort(
    (a, b) =>
      a.year - b.year ||
      (a.month ?? Number.MAX_SAFE_INTEGER) - (b.month ?? Number.MAX_SAFE_INTEGER) ||
      a.documentType.localeCompare(b.documentType, 'sv'),
  );
}
 
/**
 * Aggregate `StatskontoretBudgetRow` rows into per-year/documentType totals.
 *
 * Rows are grouped by `(year, documentType)`.  `totalBudget` and `variance`
 * are included only when every row in the group has a `budget` value.
 *
 * Returns results sorted by year ascending, then documentType alphabetically.
 */
export function summarizeBudgetOutturn(
  rows: readonly StatskontoretBudgetRow[],
): StatskontoretBudgetSummary[] {
  const groups = new Map<
    string,
    {
      year: number;
      documentType: string;
      totalOutturn: number;
      totalBudget: number;
      allHaveBudget: boolean;
      rowCount: number;
    }
  >();
 
  for (const row of rows) {
    const key = `${row.year}::${row.documentType}`;
    const existing = groups.get(key);
    if (existing) {
      existing.totalOutturn = roundOneDecimal(existing.totalOutturn + row.outturn);
      if (row.budget !== undefined) {
        existing.totalBudget = roundOneDecimal(existing.totalBudget + row.budget);
      } else {
        existing.allHaveBudget = false;
      }
      existing.rowCount++;
    } else {
      groups.set(key, {
        year: row.year,
        documentType: row.documentType,
        totalOutturn: row.outturn,
        totalBudget: row.budget ?? 0,
        allHaveBudget: row.budget !== undefined,
        rowCount: 1,
      });
    }
  }
 
  return [...groups.values()]
    .map((g): StatskontoretBudgetSummary => ({
      year: g.year,
      documentType: g.documentType,
      totalOutturn: g.totalOutturn,
      ...(g.allHaveBudget
        ? {
            totalBudget: g.totalBudget,
            variance: roundOneDecimal(g.totalOutturn - g.totalBudget),
          }
        : {}),
      rowCount: g.rowCount,
    }))
    .sort((a, b) => a.year - b.year || a.documentType.localeCompare(b.documentType, 'sv'));
}
 
/** Infer 'Inkomst' / 'Utgift' from common Swedish sheet-name patterns. */
function inferDocTypeFromSheetName(name: string): string | undefined {
  const n = name.toLowerCase();
  if (n.includes('inkomst')) return 'Inkomst';
  Eif (n.includes('utgift') || n.includes('anslag')) return 'Utgift';
  return undefined;
}