# Arbeitslosengeld Rechner - Code Structure Documentation

**Last Updated:** 2025-12-30

## Overview

The Arbeitslosengeld Rechner has been refactored to follow a modular JavaScript architecture, similar to the Minijob Rechner, for improved performance, maintainability, and code organization.

## File Structure

```
v2/
├── pages/
│   └── tools_arbeitslosengeld_rechner.php    # Main page file (PHP)
├── js/
│   └── arbeitslosengeld/
│       ├── constants.js          # ALG 1 constants (2025 values)
│       ├── constants.min.js       # Minified version
│       ├── utils.js               # Utility functions (formatting)
│       ├── utils.min.js           # Minified version
│       ├── helpers.js             # Validation and calculation helpers
│       ├── helpers.min.js          # Minified version
│       ├── export.js              # Excel/PDF export functions
│       ├── export.min.js          # Minified version
│       ├── calculator.js          # Main Alpine.js component
│       └── calculator.min.js     # Minified version
└── css/
    └── tools-pages.min.css        # Shared CSS for all tools pages
```

## Module Dependencies

The JavaScript modules must be loaded in the following order:

1. **constants.js** - Defines all ALG 1 calculation constants (max amounts, percentages, freibetrag)
2. **utils.js** - Provides formatting utilities (formatCurrency, formatNumber)
3. **helpers.js** - Contains validation and calculation helper functions
4. **export.js** - Handles Excel and PDF export functionality
5. **calculator.js** - Main Alpine.js component that ties everything together

## Module Details

### constants.js

**Purpose:** Centralized storage of all ALG 1 calculation constants for 2025.

**Exports:** `window.alg1Constants`

**Key Constants:**

- `MAX_ALG_WEST`: 2390 (€/month)
- `MAX_ALG_EAST`: 2320 (€/month)
- `ALG_PERCENTAGE_NO_CHILDREN`: 60 (%)
- `ALG_PERCENTAGE_WITH_CHILDREN`: 67 (%)
- `FREIBETRAG`: 165 (€/month)
- `BRUTTO_TO_NETTO_RATE`: 0.80 (80%)
- `SIDE_INCOME_REDUCTION_PERCENTAGE`: 0.20 (20%)
- `SIDE_INCOME_MAX_REDUCTION_PERCENTAGE`: 0.80 (80%)
- Duration calculation constants (MIN_EMPLOYMENT_MONTHS, MAX_DURATION_UNDER_50, etc.)

**Legal Basis:** SGB III §127, §150, §157

### utils.js

**Purpose:** Utility functions for formatting numbers and currency.

**Exports:** `window.alg1Utils`

**Functions:**

- `formatCurrency(value)` - Formats a number as EUR currency (e.g., "1.200,00 €")
- `formatNumber(value, decimals)` - Formats a number with specified decimal places

**Performance:** Uses cached `Intl.NumberFormat` instances for better performance.

### helpers.js

**Purpose:** Validation and calculation helper functions.

**Exports:** `window.alg1Helpers`

**Validation Functions:**

- `validateIncome(value)` - Validates income input
- `validateAge(value)` - Validates age input
- `validateEmploymentMonths(value)` - Validates employment months input
- `validateSideIncome(value)` - Validates side income input

**Calculation Functions:**

- `bruttoToNetto(brutto)` - Converts brutto to netto income
- `calculateBaseALG(nettoIncome, hasChildren)` - Calculates base ALG 1 amount
- `applyMaxCap(baseALG, region)` - Applies regional maximum cap
- `calculateDuration(employmentMonths, age)` - Calculates ALG 1 duration
- `calculateSideIncomeImpact(baseALG, sideIncome)` - Calculates side income impact

**Legal Basis:** All calculations follow SGB III regulations.

### export.js

**Purpose:** Handles Excel and PDF export functionality.

**Exports:** `window.alg1Export`

**Functions:**

- `exportExcel(calcData, formatCurrency)` - Exports calculation results to Excel
- `exportPDF(calcData, formatCurrency)` - Exports calculation results to PDF

**Dependencies:**

- Excel export: `/v2/api/export-tool-excel.php`
- PDF export: jsPDF library (loaded via CDN)

### calculator.js

**Purpose:** Main Alpine.js component that orchestrates the calculator functionality.

**Exports:** `window.arbeitslosengeldRechner`

**Component Structure:**

- **Inputs:** incomeType, incomeAmount, age, hasChildren, employmentMonths, sideIncome, region
- **Results:** alg1Amount, duration, calculationBreakdown, sideIncomeImpact
- **UI State:** showAdvanced, hasError, errorMessage, showResults

**Methods:**

- `init()` - Initializes component, sets up watchers
- `debouncedCalculate()` - Debounced calculation trigger
- `calculate()` - Main calculation logic (uses helpers)
- `validateInputs()` - Validates all inputs (uses helpers)
- `formatCurrency(value)` - Formats currency (uses utils)
- `formatNumber(value, decimals)` - Formats numbers (uses utils)
- `getCalculationData()` - Returns calculation data object
- `exportExcel()` - Triggers Excel export (uses export module)
- `exportPDF()` - Triggers PDF export (uses export module)

**Dependencies:** Requires all other modules (constants, utils, helpers, export) to be loaded first.

## Loading Order in PHP

The modules are loaded in the `<head>` section of `tools_arbeitslosengeld_rechner.php`:

```php
<!-- ALG 1 Calculator JavaScript Modules (load in order: constants -> utils -> helpers -> export -> calculator) -->
<script src="/v2/js/arbeitslosengeld/constants.min.js?v=<?php echo filemtime(__DIR__ . '/../js/arbeitslosengeld/constants.min.js'); ?>"></script>
<script src="/v2/js/arbeitslosengeld/utils.min.js?v=<?php echo filemtime(__DIR__ . '/../js/arbeitslosengeld/utils.min.js'); ?>"></script>
<script src="/v2/js/arbeitslosengeld/helpers.min.js?v=<?php echo filemtime(__DIR__ . '/../js/arbeitslosengeld/helpers.min.js'); ?>"></script>
<script src="/v2/js/arbeitslosengeld/export.min.js?v=<?php echo filemtime(__DIR__ . '/../js/arbeitslosengeld/export.min.js'); ?>"></script>
<script src="/v2/js/arbeitslosengeld/calculator.min.js?v=<?php echo filemtime(__DIR__ . '/../js/arbeitslosengeld/calculator.min.js'); ?>"></script>
```

**Note:** The `.min.js` files are generated automatically by running `npm run minify`. The `filemtime()` function is used for cache busting.

## Benefits of Modular Structure

1. **Performance:**

   - Smaller, focused files enable better browser caching
   - Only changed modules need to be re-downloaded
   - Minified files reduce total download size (~70% reduction)

2. **Maintainability:**

   - Clear separation of concerns
   - Easy to locate and modify specific functionality
   - Constants can be updated in one place

3. **Reusability:**

   - Helper functions can be reused in other calculators
   - Constants can be shared across related tools
   - Export functions follow a consistent pattern

4. **Testing:**

   - Each module can be tested independently
   - Easier to write unit tests for pure functions
   - Calculation logic is isolated from UI logic

5. **Documentation:**
   - Each module has a clear purpose and API
   - JSDoc comments explain function parameters and return values
   - Legal basis is documented in constants and helpers

## Minification

All JavaScript files are automatically minified using `npm run minify`. The minification script (`minify-assets.js`) includes:

```javascript
'v2/js/arbeitslosengeld/constants.js',
'v2/js/arbeitslosengeld/utils.js',
'v2/js/arbeitslosengeld/helpers.js',
'v2/js/arbeitslosengeld/export.js',
'v2/js/arbeitslosengeld/calculator.js',
```

**Minification Results:**

- constants.js: 1.8 KB → 367 B (80% smaller)
- utils.js: 2.7 KB → 829 B (70% smaller)
- helpers.js: 9.8 KB → 2.9 KB (71% smaller)
- export.js: 8.4 KB → 3.5 KB (59% smaller)
- calculator.js: 12.4 KB → 5 KB (60% smaller)

**Total:** ~35 KB → ~13 KB (63% reduction)

## CSS Structure

The page uses:

- **Shared CSS:** `/v2/css/tools-pages.min.css` (loaded asynchronously)
- **Critical CSS:** Inline in `<style>` tag for above-fold content (background pattern, x-cloak, performance optimizations)

This follows best practices for performance optimization.

## Future Improvements

1. **TypeScript:** Consider migrating to TypeScript for better type safety
2. **Unit Tests:** Add comprehensive unit tests for each module
3. **ES Modules:** Consider using ES modules instead of global window objects
4. **Tree Shaking:** Use a bundler to enable tree shaking for even smaller bundles

## Related Documentation

- [ALG 1 Legal Research](./alg1-legal-research-2025.md)
- [ALG 1 Calculation Formulas](./alg1-calculation-formulas-2025.md)
- [E2E Test Results](./arbeitslosengeld-rechner-e2e-test-results.md)
- [Manual Testing Guide](./arbeitslosengeld-rechner-manual-testing-guide.md)
