## Summary
Step 4 of the analytics plan, items 2, 4 and 5: **income, net and assets views** on the Analyse page (replacing the old Vermögen chart page) and a **narrow-screen layout** pass.
### Views
A switch at the top selects **Ausgaben | Einnahmen | Netto | Vermögen**, stored in the URL as `view=`. Switching starts the drill-down from the top, because the subclasses differ per view.
- **Einnahmen:** works like Ausgaben. Bookings *from* an income account count positive, bookings *to* one (corrections) negative.
- **Netto:** income minus expenses. Income subclasses are positive and expense subclasses negative.
- The bar chart stacks income up and expenses down, with a black line for the net result per period; the tooltip total is left out there.
- Categories are ordered by size, so the big expense groups aren't folded into "Andere".
- The fourth tile shows the **savings rate** (net / income).
- No treemap, since areas can't show negative amounts.
- **Vermögen:** month-end balances of the asset accounts (class 1) in CHF. It is a stock, not a flow:
- A month, quarter or year shows the balance at its end, and the total is the balance at the end of the range.
- Tiles show that balance, the change since the start of the range (with the opening balance), and the comparison with the same month a year earlier.
- The year table shows year-end balances; the drill-down ends at the account.
- The year comparison shows month-end balances, without the cumulative switch.
- Foreign-currency balances are computed like the balance sheet (`ViewService`): kept in the account currency and converted with `IFxConverter`, which is asked once per currency.
- **Colours follow the view:** more expenses are red; more income, surplus or assets green. The CSS classes are now `worse` / `better` instead of `up` / `down`.
### Code
- `ExpenseAnalysis` → **`AccountingAnalysis`** with `AnalyticsView` (Expenses, Income, Net, Assets), and `GetExpenseAnalysisAsync` → `GetAnalysisAsync`. The running year's last month now comes from all bookings, not just expenses.
- `AnalyticsResult.Opening` gives the balance at the start of the range for Vermögen.
- `charts.js`: the stacked bar chart takes an optional `totalLine`.
### Removed
- The **Vermögen** chart page (`/Assets`) and its menu entry. Plotly is now only used by the booking-text charts on the Transactions page.
### Narrow screens
At 400 px the page was wider than the screen.
- **App-wide:** the side menu took half the screen. It now starts collapsed to icons below 700 px (`wwwroot/js/viewport.js`); the ☰ toggle still opens it. The header dropdowns are narrower, and the app name hides below 520 px.
- **Analyse page:** button groups wrap, the tiles sit two per row, and in the year table the name column is narrower and pinned while the years scroll, with the full name as a tooltip.
## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 88/88 pass, including 7 new `AccountingAnalysisTestShould` tests (income signs, net ordering, month-end balances with opening, balance at period end, FX conversion asked once, comparison at the same month, assets drill-down ends at the account)
- [x] Against a copy of the real data, all matching the app's own reports:
- Einnahmen 2026 = 109'865.13 ("Total Einkünfte" in the profit-and-loss report)
- Netto 2026 = 32'859.06 (= 109'865.13 − 77'006.07)
- Vermögen end of Oct 2026 = 263'994.98 ("Total Aktiven" in the Bilanz)
- [x] Headless Chrome at 400, 820 and 1500 px: no horizontal overflow; menu collapsed at 400 px and expanded at 820 / 1500 px; pinned table column scrolls correctly; all charts render without console errors
## Note on the data (not a code issue)
The Vermögen view shows each year as its books say. In the real data, some closing balances don't match the next year's opening balances. These are probably bookings added to a year after the next one was opened:
- End of 2024 → 2025: Bargeld CHF (+40.75)
- End of 2025 → 2026: Bargeld CHF (+98.50), TKB Privatkonto (+200.00), account 1042 (2'030.40 at the end of 2025, missing in 2026), Durchlaufskonto (−7.29)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #6
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
280 lines
10 KiB
JavaScript
280 lines
10 KiB
JavaScript
// Thin Chart.js wrapper for Blazor (see ChartJsChart.razor). Chart.js and the treemap plugin are
|
||
// loaded on first use from wwwroot/lib, so pages without charts don't pay for them.
|
||
|
||
const scripts = new Map();
|
||
|
||
function loadScript(src) {
|
||
if (!scripts.has(src)) {
|
||
scripts.set(src, new Promise((resolve, reject) => {
|
||
const script = document.createElement('script');
|
||
script.src = src;
|
||
script.onload = resolve;
|
||
script.onerror = () => reject(new Error(`${src} could not be loaded`));
|
||
document.head.appendChild(script);
|
||
}));
|
||
}
|
||
return scripts.get(src);
|
||
}
|
||
|
||
async function loadChartJs(kind) {
|
||
await loadScript('lib/chartjs/chart.umd.min.js');
|
||
if (kind === 'treemap') {
|
||
// Registers itself with the global Chart.
|
||
await loadScript('lib/chartjs-chart-treemap/chartjs-chart-treemap.min.js');
|
||
}
|
||
window.Chart.defaults.font.family = theme.font;
|
||
}
|
||
|
||
// Same look as ChartTheme.cs.
|
||
const theme = {
|
||
font: "'Helvetica Neue', Helvetica, Arial, sans-serif",
|
||
ink: '#0b0b0b',
|
||
muted: '#52514e',
|
||
grid: '#e1e0d9',
|
||
surface: '#fcfcfb'
|
||
};
|
||
|
||
// de-CH uses a typographic apostrophe; the rest of the app (Formatting.cs) uses a plain one.
|
||
const amount = new Intl.NumberFormat('de-CH', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||
const axisAmount = new Intl.NumberFormat('de-CH', { maximumFractionDigits: 0 });
|
||
const formatChf = value => amount.format(value).replace(/’/g, "'");
|
||
const formatAxis = value => axisAmount.format(value).replace(/’/g, "'");
|
||
|
||
// Treemap tile helpers: level 0 tiles are parents (their group value is the parent id); level 1
|
||
// tiles keep the original tree items, which carry the parent id.
|
||
const parentOf = raw => raw.l === 0 ? raw.g : raw._data.children[0].p;
|
||
const isParentGroup = (raw, items) => raw.l === 0 && items.some(i => i.c);
|
||
|
||
function withAlpha(hex, alpha) {
|
||
const n = parseInt(hex.slice(1), 16);
|
||
return `rgba(${n >> 16}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
|
||
}
|
||
|
||
const tooltip = {
|
||
backgroundColor: '#ffffff',
|
||
borderColor: theme.grid,
|
||
borderWidth: 1,
|
||
titleColor: theme.ink,
|
||
bodyColor: theme.ink,
|
||
footerColor: theme.ink,
|
||
titleFont: { weight: 'bold' },
|
||
footerFont: { weight: 'bold' },
|
||
padding: 10,
|
||
usePointStyle: true
|
||
};
|
||
|
||
const legend = {
|
||
position: 'bottom',
|
||
labels: { usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, color: theme.muted, font: { size: 12 } }
|
||
};
|
||
|
||
const amountAxis = {
|
||
grid: { color: theme.grid },
|
||
border: { display: false },
|
||
title: { display: true, text: 'CHF', color: theme.muted },
|
||
ticks: { color: theme.muted, callback: value => formatAxis(value) }
|
||
};
|
||
|
||
const categoryAxis = { grid: { display: false }, ticks: { color: theme.muted } };
|
||
|
||
// Each kind turns the data sent from Blazor into Chart.js data, and builds its options once.
|
||
// Options read the current data through state(), so update() only has to swap the data.
|
||
const kinds = {
|
||
// data: { labels, series: [{ name, color, values, clickable }], totalLine?: { name, values } };
|
||
// click key = series index. The optional line (e.g. the net result) is its own stack, so it
|
||
// shows its value instead of stacking onto the bars.
|
||
stackedBar: {
|
||
type: 'bar',
|
||
data: data => ({
|
||
labels: data.labels,
|
||
datasets: [...data.series.map(s => ({
|
||
label: s.name,
|
||
data: s.values,
|
||
backgroundColor: s.color,
|
||
hoverBackgroundColor: s.color,
|
||
borderColor: theme.surface,
|
||
borderWidth: { top: 1 },
|
||
borderRadius: 3,
|
||
stack: 'total',
|
||
clickable: s.clickable
|
||
})), ...(data.totalLine ? [{
|
||
type: 'line',
|
||
label: data.totalLine.name,
|
||
data: data.totalLine.values,
|
||
stack: 'line',
|
||
borderColor: theme.ink,
|
||
backgroundColor: theme.ink,
|
||
borderWidth: 2,
|
||
pointRadius: 2,
|
||
tension: 0.25,
|
||
order: -1
|
||
}] : [])]
|
||
}),
|
||
options: () => ({
|
||
interaction: { mode: 'index', intersect: false },
|
||
plugins: {
|
||
legend,
|
||
tooltip: {
|
||
...tooltip,
|
||
filter: item => item.parsed.y !== 0,
|
||
itemSort: (a, b) => b.parsed.y - a.parsed.y,
|
||
callbacks: {
|
||
label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} CHF`,
|
||
footer: items => {
|
||
const bars = items.filter(i => i.dataset.type !== 'line');
|
||
return bars.length === items.length
|
||
? `Total: ${formatChf(bars.reduce((sum, i) => sum + i.parsed.y, 0))} CHF`
|
||
: '';
|
||
}
|
||
}
|
||
}
|
||
},
|
||
scales: { x: { ...categoryAxis, stacked: true }, y: { ...amountAxis, stacked: true } }
|
||
}),
|
||
hit: (chart, event) => {
|
||
const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0];
|
||
return hit && chart.data.datasets[hit.datasetIndex].clickable ? String(hit.datasetIndex) : null;
|
||
}
|
||
},
|
||
|
||
// data: { labels, series: [{ name, color, values (null = no data), width }] }; not clickable
|
||
line: {
|
||
type: 'line',
|
||
data: data => ({
|
||
labels: data.labels,
|
||
datasets: data.series.map(s => ({
|
||
label: s.name,
|
||
data: s.values,
|
||
borderColor: s.color,
|
||
backgroundColor: s.color,
|
||
borderWidth: s.width,
|
||
pointRadius: s.width > 2 ? 3 : 2,
|
||
pointHoverRadius: 5,
|
||
tension: 0.25,
|
||
spanGaps: false
|
||
}))
|
||
}),
|
||
options: () => ({
|
||
interaction: { mode: 'index', intersect: false },
|
||
plugins: {
|
||
legend: { ...legend, labels: { ...legend.labels, pointStyle: 'line' } },
|
||
tooltip: {
|
||
...tooltip,
|
||
filter: item => item.parsed.y !== null,
|
||
itemSort: (a, b) => b.parsed.y - a.parsed.y,
|
||
callbacks: { label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} CHF` }
|
||
}
|
||
},
|
||
scales: { x: categoryAxis, y: amountAxis }
|
||
}),
|
||
hit: () => null
|
||
},
|
||
|
||
// data: { items: [{ p, c, value }], names: { id: name }, colors: { p: color }, clickable: [key] }
|
||
// p = parent id, c = child id (null for a single level); click key = "p" or "p|c"
|
||
treemap: {
|
||
type: 'treemap',
|
||
data: data => ({
|
||
datasets: [{
|
||
tree: data.items,
|
||
key: 'value',
|
||
groups: data.items.some(i => i.c) ? ['p', 'c'] : ['p'],
|
||
spacing: 1,
|
||
borderWidth: 0,
|
||
borderRadius: 3,
|
||
backgroundColor: ctx => {
|
||
if (ctx.type !== 'data') {
|
||
return 'transparent';
|
||
}
|
||
const color = data.colors[parentOf(ctx.raw)] ?? '#898781';
|
||
return withAlpha(color, isParentGroup(ctx.raw, data.items) ? 0.25 : 0.9);
|
||
},
|
||
captions: {
|
||
display: true,
|
||
color: theme.ink,
|
||
font: { weight: 'bold', size: 12 },
|
||
formatter: ctx => `${data.names[ctx.raw.g]} ${formatAxis(ctx.raw.v)}`
|
||
},
|
||
labels: {
|
||
display: true,
|
||
color: '#ffffff',
|
||
font: [{ size: 12, weight: 'bold' }, { size: 11 }],
|
||
overflow: 'hidden',
|
||
formatter: ctx => [data.names[ctx.raw.g], `${formatAxis(ctx.raw.v)} CHF`]
|
||
}
|
||
}]
|
||
}),
|
||
options: state => ({
|
||
plugins: {
|
||
legend: { display: false },
|
||
tooltip: {
|
||
...tooltip,
|
||
displayColors: false,
|
||
callbacks: {
|
||
title: items => {
|
||
const raw = items[0].raw;
|
||
const names = state().names;
|
||
return raw.l === 0 ? names[raw.g] : `${names[parentOf(raw)]} › ${names[raw.g]}`;
|
||
},
|
||
label: item => `${formatChf(item.raw.v)} CHF`
|
||
}
|
||
}
|
||
}
|
||
}),
|
||
hit: (chart, event) => {
|
||
// Deepest tile under the pointer: an account inside a subclass wins over the subclass.
|
||
const hits = chart.getElementsAtEventForMode(event, 'point', { intersect: true }, false);
|
||
const data = chart.data.datasets[0].data;
|
||
const raw = hits.map(h => data[h.index]).sort((a, b) => b.l - a.l)[0];
|
||
if (!raw) {
|
||
return null;
|
||
}
|
||
const key = raw.l === 0 ? raw.g : `${parentOf(raw)}|${raw.g}`;
|
||
return chart.$clickable?.includes(key) ? key : null;
|
||
}
|
||
}
|
||
};
|
||
|
||
/**
|
||
* Creates a chart of the given kind on the canvas and returns a handle with update/destroy.
|
||
* Clicking a clickable element calls dotNetRef.OnChartClicked(key); see the kinds above for keys.
|
||
*/
|
||
export async function createChart(canvas, kind, data, dotNetRef) {
|
||
await loadChartJs(kind);
|
||
const spec = kinds[kind];
|
||
let current = data;
|
||
|
||
const chart = new window.Chart(canvas, {
|
||
type: spec.type,
|
||
data: spec.data(current),
|
||
options: {
|
||
responsive: true,
|
||
maintainAspectRatio: false,
|
||
animation: { duration: 250 },
|
||
...spec.options(() => current),
|
||
onHover: (event, _, chart) => {
|
||
event.native.target.style.cursor = spec.hit(chart, event) !== null ? 'pointer' : 'default';
|
||
},
|
||
onClick: (event, _, chart) => {
|
||
const key = spec.hit(chart, event);
|
||
if (key !== null) {
|
||
dotNetRef.invokeMethodAsync('OnChartClicked', key);
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
chart.$clickable = current.clickable;
|
||
|
||
return {
|
||
update(newData) {
|
||
current = newData;
|
||
chart.$clickable = current.clickable;
|
||
chart.data = spec.data(current);
|
||
chart.update();
|
||
},
|
||
destroy() {
|
||
chart.destroy();
|
||
}
|
||
};
|
||
}
|