diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6cb1766..dca475e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,21 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/).
+## [1.1.0] - 2026-10-04
+
+### Added
+
+- Payment history for each subscription: past charges are calculated from the start date, frequency and price, and the total paid so far is shown.
+- Confirm the amount actually paid for any charge, or mark it as not charged.
+- Price history: when the price changes you choose whether it applies from the next renewal, from the last charge, or to the whole history.
+- Pausing a subscription stops its charges; resuming marks the renewals in between as not charged.
+- "Actual spending" section with the last 12 months and year to date, plus a monthly bar chart.
+- Price history and confirmed charges are included in the JSON backup.
+
+### Fixed
+
+- The billing frequency selector overflowed the screen on narrow phones (iPhone SE/mini).
+
## [1.0.2] - 2026-10-04
### Fixed
diff --git a/README.it.md b/README.it.md
index 551e309..31fc013 100644
--- a/README.it.md
+++ b/README.it.md
@@ -26,6 +26,7 @@
- **Frequenza flessibile**: mensile, trimestrale, annuale o personalizzata ("ogni 4 mesi", "ogni 2 settimane", …). Le date di fine mese sono gestite correttamente (31 gen → 28/29 feb → 31 mar).
- **Multivaluta**: ogni abbonamento ha la sua valuta. I totali sono mostrati per valuta, oppure come totale unico nella valuta principale se inserisci i tuoi tassi di cambio (i tassi non vengono mai scaricati da internet).
- **Dashboard**: spesa mensile o annuale, rinnovi dei prossimi 30 giorni, ordinamento per rinnovo, costo o nome, e pausa degli abbonamenti senza eliminarli.
+- **Storico pagamenti**: gli addebiti passati vengono calcolati in automatico, e puoi confermare l'importo pagato davvero o segnare un addebito come non avvenuto. Le variazioni di prezzo valgono dalla data che scegli, così lo storico resta corretto. Il grafico "Spesa effettiva" mostra gli ultimi 12 mesi.
- **Promemoria**: notifiche locali più un **export nel calendario (.ics)** con avvisi, per promemoria affidabili su qualsiasi telefono.
- **PWA installabile**: funziona offline e si apre a schermo intero. Una guida animata mostra come aggiungere l'app alla schermata Home su iOS e Android.
- **Interfaccia bilingue**: italiano e inglese, con rilevamento automatico e selettore manuale.
diff --git a/README.md b/README.md
index 5ac3ece..4fa8bb4 100644
--- a/README.md
+++ b/README.md
@@ -39,6 +39,7 @@
- **Flexible billing**: monthly, quarterly or yearly, or any custom period ("every 4 months", "every 2 weeks", …). Month-end dates are handled correctly (31 Jan → 28/29 Feb → 31 Mar).
- **Multi-currency**: each subscription has its own currency. Totals are shown per currency, or as one total in your main currency if you enter your own exchange rates (rates are never fetched online).
- **Dashboard**: monthly or yearly spend, upcoming renewals for the next 30 days, sorting by renewal date, cost or name, and pausing a subscription without deleting it.
+- **Payment history**: past charges are calculated automatically, and you can confirm the amount actually paid or mark a charge as not charged. Price changes apply from a date of your choice, so the history stays accurate. An "Actual spending" chart shows the last 12 months.
- **Reminders**: local notifications plus a **calendar export (.ics)** with alerts for reliable reminders on any phone.
- **Installable PWA**: works offline and opens full screen. An animated guide shows how to add the app to the Home Screen on iOS and Android.
- **Bilingual UI**: Italian and English, detected automatically and switchable.
@@ -147,6 +148,7 @@ For reminders that always arrive on time, use **Settings → Export to calendar*
│ │ ├── db.js IndexedDB storage, validation, backup
│ │ ├── reminders.js Local notifications
│ │ ├── ics.js Calendar export
+│ │ ├── history.js Payment history and actual spending
│ │ └── version.js App version (also names the offline cache)
│ ├── ui.js DOM helpers, bottom sheets, toasts
│ ├── install.js "Add to Home Screen" guide
diff --git a/css/app.css b/css/app.css
index 4ab1e51..57958b3 100644
--- a/css/app.css
+++ b/css/app.css
@@ -542,7 +542,7 @@ dialog.sheet.open .sheet-panel { transform: translate(-50%, 0); }
/* ---------- Form ---------- */
-.form { display: grid; gap: 16px; }
+.form { display: grid; grid-template-columns: minmax(0, 1fr); gap: 16px; }
.form-hero { display: grid; justify-items: center; gap: 10px; padding: 6px 0 4px; }
.form-hero .logo { animation: pop 0.45s var(--ease-spring) backwards; }
.hero-name { font-size: 20px; font-weight: 750; text-align: center; overflow-wrap: anywhere; }
@@ -639,7 +639,7 @@ input[type="date"]::-webkit-date-and-time-value { text-align: left; }
/* ---------- Settings ---------- */
-.settings { display: grid; gap: 22px; }
+.settings { display: grid; grid-template-columns: minmax(0, 1fr); gap: 22px; }
.set-group h3 {
margin: 0 4px 8px;
font-size: 13px;
@@ -831,3 +831,122 @@ input[type="date"]::-webkit-date-and-time-value { text-align: left; }
}
.fatal, .noscript { padding: 24px; text-align: center; color: var(--danger); }
+
+/* ---------- Payment history ---------- */
+
+.history-card {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ width: 100%;
+ padding: 14px 16px;
+ border: 0;
+ border-radius: var(--radius-sm);
+ background: var(--surface);
+ box-shadow: inset 0 0 0 1px var(--line);
+ text-align: left;
+ transition: background 0.15s ease;
+}
+.history-card:active { background: var(--surface-2); }
+.history-card-text { flex: 1; min-width: 0; display: grid; gap: 2px; }
+.history-card-total { font-size: 20px; font-weight: 750; font-variant-numeric: tabular-nums; }
+.history-card .chev { width: 18px; height: 18px; color: var(--muted); }
+
+.history { display: grid; grid-template-columns: minmax(0, 1fr); gap: 18px; }
+.history-head { display: flex; align-items: center; gap: 14px; padding-top: 4px; }
+.history-total { font-size: 30px; font-weight: 800; letter-spacing: -0.03em; font-variant-numeric: tabular-nums; line-height: 1.1; }
+.history-hint { margin-top: -6px; }
+.charge-list, .price-list { list-style: none; margin: 0; padding: 0; }
+.charge-row {
+ display: grid;
+ grid-template-columns: 1fr auto auto;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ min-height: 56px;
+ padding: 10px 16px;
+ border: 0;
+ background: transparent;
+ text-align: left;
+ color: var(--text);
+ transition: background 0.15s ease;
+}
+.charge-row:active:not(:disabled) { background: var(--surface-2); }
+.charge-row:disabled { cursor: default; opacity: 0.7; }
+.charge-date { font-weight: 600; font-variant-numeric: tabular-nums; }
+.charge-amount { display: grid; justify-items: end; gap: 1px; font-weight: 700; font-variant-numeric: tabular-nums; min-width: 72px; }
+.charge-row.is-skipped .charge-amount > span:first-child { color: var(--muted); }
+.chip-status {
+ padding: 2px 8px;
+ border-radius: 999px;
+ font-size: 11.5px;
+ font-weight: 700;
+ white-space: nowrap;
+ background: var(--surface-2);
+ color: var(--muted);
+}
+.chip-status.st-paid { background: color-mix(in srgb, var(--ok) 16%, transparent); color: var(--ok); }
+.chip-status.st-skipped { background: color-mix(in srgb, var(--danger) 12%, transparent); color: var(--danger); }
+.chip-status.st-upcoming { background: var(--accent-soft); color: var(--accent); }
+.price-list .set-row { min-height: 48px; }
+.show-all { margin-top: 10px; }
+.currency-static { display: flex; align-items: center; justify-content: center; font-weight: 650; color: var(--muted); }
+
+/* ---------- Actual spending ---------- */
+
+.spend-card {
+ padding: 16px;
+ border-radius: var(--radius);
+ background: var(--surface);
+ box-shadow: var(--shadow);
+}
+.spend-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
+.spend-stats .label { font-size: 13px; font-weight: 650; color: var(--muted); }
+.spend-value { font-size: 22px; font-weight: 750; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; margin-top: 2px; }
+.spend-readout { margin-top: 14px; font-size: 13.5px; font-weight: 650; color: var(--muted); font-variant-numeric: tabular-nums; min-height: 1.4em; }
+.bars {
+ display: grid;
+ grid-template-columns: repeat(12, 1fr);
+ gap: 4px;
+ height: 140px;
+ margin-top: 8px;
+ border-bottom: 1px solid var(--line);
+}
+.bar {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+ align-items: center;
+ height: 100%;
+ padding: 0 0 2px;
+ border: 0;
+ background: transparent;
+ cursor: pointer;
+}
+.bar-fill {
+ width: min(100%, 18px);
+ height: var(--h, 0%);
+ min-height: 3px;
+ border-radius: 4px 4px 0 0;
+ background: var(--accent);
+ transition: filter 0.15s ease, height 0.4s var(--ease-spring);
+}
+.bar-fill.is-zero { min-height: 0; }
+.bar.is-active .bar-fill, .bar:hover .bar-fill { filter: brightness(1.15) saturate(1.1); }
+.bar-label {
+ position: absolute;
+ bottom: -22px;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--muted);
+}
+.bar.is-current .bar-label { color: var(--text); font-weight: 750; }
+.spend-card .bars { margin-bottom: 22px; }
+.spend-note { margin-top: 4px; }
+
+/* Narrow phones (iPhone SE/mini): the four frequency options don't fit in one row. */
+@media (max-width: 420px) {
+ .form .seg { display: grid; grid-template-columns: 1fr 1fr; }
+ .seg button { min-width: 0; }
+}
diff --git a/index.html b/index.html
index f8900a6..55deda4 100644
--- a/index.html
+++ b/index.html
@@ -50,6 +50,10 @@
@@ -77,6 +81,7 @@
+
diff --git a/js/app.js b/js/app.js
index 705d76d..4536e88 100644
--- a/js/app.js
+++ b/js/app.js
@@ -4,7 +4,7 @@
(function (g) {
'use strict';
const ST = g.ST;
- const { db, schedule, catalog, i18n, ui, reminders } = ST;
+ const { db, schedule, catalog, i18n, ui, reminders, history } = ST;
const { h, append, icon, logo, sheet, toast, haptic } = ui;
const t = (...a) => i18n.t(...a);
@@ -97,11 +97,15 @@
function enrich(sub, today) {
const next = schedule.nextRenewal(sub.startDate, sub.freq, today);
+ // A price change can be scheduled for a later renewal: use the price in
+ // force at the next one.
+ const price = next ? history.priceAt(sub, schedule.toISO(next)) : sub.price;
return {
sub,
next,
+ price,
days: next ? schedule.diffDays(today, next) : Infinity,
- monthly: schedule.monthlyCost(sub.price, sub.freq),
+ monthly: schedule.monthlyCost(price, sub.freq),
};
}
@@ -145,10 +149,12 @@
$('summary').hidden = empty;
$('upcoming-section').hidden = empty;
$('list-section').hidden = empty;
+ $('spend-section').hidden = empty;
if (empty) return;
renderSummary(rows);
renderUpcoming(rows);
renderList(rows);
+ renderSpend();
}
function renderSummary(rows) {
@@ -220,7 +226,7 @@
logo(r.sub, 'sm'),
h('span', { class: 'up-name', text: r.sub.name }),
h('span', { class: 'up-when', text: i18n.relDays(r.days, r.next) }),
- h('span', { class: 'up-price', text: i18n.fmtMoney(r.sub.price, r.sub.currency) }))));
+ h('span', { class: 'up-price', text: i18n.fmtMoney(r.price, r.sub.currency) }))));
}
function renderList(rowsArg) {
@@ -251,7 +257,7 @@
sub.active ? null : h('span', { class: 'badge', text: t('list.paused') }),
meta)),
h('span', { class: 'sub-price' },
- h('span', { class: 'price', text: i18n.fmtMoney(sub.price, sub.currency) }),
+ h('span', { class: 'price', text: i18n.fmtMoney(r.price, sub.currency) }),
sub.freq.unit !== 'month' || sub.freq.every !== 1
? h('span', { class: 'per', text: `≈ ${i18n.fmtMoney(r.monthly, sub.currency)}${t('per.month')}` })
: null)));
@@ -495,6 +501,7 @@
const preview = h('p', { class: 'preview', 'aria-live': 'polite' });
function updatePreview() {
+ if (editing) updatePriceScope();
const p = parsePrice(price.value);
const next = schedule.nextRenewal(start.value, freq);
if (!next || !Number.isFinite(p)) {
@@ -518,11 +525,60 @@
header.replaceChildren(logo(preview, 'lg'), h('p', { class: 'hero-name', text: name.value || t('form.new') }));
}
+ // When the price of an existing subscription changes, ask from when the
+ // new price applies, so past charges keep the price actually paid.
+ const priceScope = h('select', { class: 'input' });
+ const priceScopeField = h('div', { class: 'field', hidden: true },
+ h('label', { for: 'f-price-scope', text: t('price.apply') }),
+ Object.assign(priceScope, { id: 'f-price-scope' }));
+ function updatePriceScope() {
+ const p = parsePrice(price.value);
+ const tomorrow = schedule.addDays(schedule.today(), 1);
+ const last = schedule.parseISO(start.value) && schedule.isValidFreq(freq)
+ ? schedule.previousRenewal(start.value, freq, tomorrow) : null;
+ const show = editing && Number.isFinite(p) && p !== opts.sub.price && !!last;
+ priceScopeField.hidden = !show;
+ if (!show) return;
+ const next = schedule.nextRenewal(start.value, freq, tomorrow);
+ const prev = priceScope.value;
+ const fmt = (d) => i18n.fmtDate(d, { day: 'numeric', month: 'short', year: 'numeric' });
+ priceScope.replaceChildren(
+ h('option', { value: schedule.toISO(next), text: t('price.fromNext', { date: fmt(next) }) }),
+ h('option', { value: schedule.toISO(last), text: t('price.fromLast', { date: fmt(last) }) }),
+ h('option', { value: 'all', text: t('price.all') }));
+ if ([...priceScope.options].some((o) => o.value === prev)) priceScope.value = prev;
+ }
+ if (editing) {
+ price.addEventListener('input', updatePriceScope);
+ start.addEventListener('input', updatePriceScope);
+ }
+
for (const el of [price, start]) el.addEventListener('input', updatePreview);
currency.addEventListener('change', updatePreview);
name.addEventListener('input', drawHero);
color.addEventListener('input', drawHero);
+ const historyCard = editing ? h('button', { type: 'button', class: 'history-card' }) : null;
+ function drawHistoryCard() {
+ if (!historyCard) return;
+ const cur = state.subs.find((x) => x.id === opts.sub.id) || opts.sub;
+ const sum = history.summary(cur, schedule.today());
+ const sub2 = sum.count
+ ? i18n.tp('history.count', sum.count, { date: i18n.fmtDate(sum.since) })
+ : t('history.none', { date: i18n.fmtDate(schedule.nextRenewal(cur.startDate, cur.freq) || schedule.today()) });
+ historyCard.replaceChildren(
+ h('span', { class: 'history-card-text' },
+ h('span', { class: 'label', text: t('history.paidSoFar') }),
+ h('span', { class: 'history-card-total', text: i18n.fmtMoney(sum.total, cur.currency) }),
+ h('span', { class: 'hint', text: sub2 })),
+ icon('chevron', 'chev'));
+ }
+ if (historyCard) {
+ historyCard.setAttribute('aria-label', t('history.open'));
+ historyCard.addEventListener('click', () => openHistory(opts.sub.id, drawHistoryCard));
+ drawHistoryCard();
+ }
+
const priceWrap = h('div', { class: 'field' },
h('label', { for: 'f-price', text: t('form.price') }),
h('div', { class: 'price-row' }, Object.assign(price, { id: 'f-price' }), currency),
@@ -533,8 +589,10 @@
const form = h('form', { class: 'form', novalidate: true },
header,
+ historyCard,
nameField,
priceWrap,
+ priceScopeField,
h('div', { class: 'field' },
h('span', { class: 'label', text: t('form.frequency') }),
seg, customRow, freqError),
@@ -596,11 +654,30 @@
target.focus();
return;
}
+ // Start from the stored copy: the history sheet may have changed it.
+ const stored = editing ? (state.subs.find((x) => x.id === opts.sub.id) || opts.sub) : {};
+ const today = schedule.today();
+ const nowActive = editing ? active.checked : true;
+ let priceHistory;
+ if (!editing) priceHistory = [{ from: start.value, price: p }];
+ else if (p !== stored.price) {
+ const scope = priceScopeField.hidden ? 'all' : priceScope.value;
+ priceHistory = history.withPrice({ ...stored, startDate: start.value }, p, scope);
+ } else priceHistory = stored.priceHistory;
+ let { pausedAt = null, charges = {} } = stored;
+ if (editing && stored.active && !nowActive) pausedAt = schedule.toISO(today);
+ if (editing && !stored.active && nowActive) {
+ charges = { ...history.skippedWhilePaused({ ...stored, startDate: start.value, freq }, today), ...charges };
+ pausedAt = null;
+ }
const data = {
- ...(opts.sub || {}),
+ ...stored,
catalogId: base.catalogId,
name: name.value,
price: p,
+ priceHistory,
+ charges,
+ pausedAt,
currency: currency.value,
freq,
startDate: start.value,
@@ -608,13 +685,10 @@
color: base.catalogId ? base.color : color.value.slice(1),
reminder: parseInt(reminder.value, 10),
notes: notes.value,
- active: editing ? active.checked : true,
+ active: nowActive,
};
try {
- const saved = await db.put(data);
- const i = state.subs.findIndex((x) => x.id === saved.id);
- if (i >= 0) state.subs[i] = saved;
- else state.subs.push(saved);
+ await saveSub(data);
haptic(12);
s.close('saved');
render();
@@ -630,6 +704,222 @@
if (!editing && !base.name && g.matchMedia('(pointer: fine)').matches) name.focus();
}
+ // ---------- Payment history ----------
+
+ async function saveSub(next) {
+ const saved = await db.put(next);
+ const i = state.subs.findIndex((x) => x.id === saved.id);
+ if (i >= 0) state.subs[i] = saved;
+ else state.subs.push(saved);
+ return saved;
+ }
+
+ function openHistory(id, onChange) {
+ const SHOWN = 12;
+ let expanded = false;
+ const body = h('div', { class: 'history' });
+ const s = sheet({ title: t('history.title'), className: 'sheet-tall', body });
+
+ function changed() {
+ draw();
+ render();
+ if (onChange) onChange();
+ }
+
+ function draw() {
+ const sub = state.subs.find((x) => x.id === id);
+ if (!sub) { s.close(); return; }
+ const today = schedule.today();
+ const sum = history.summary(sub, today);
+ // Everything up to today plus the next upcoming charge, newest first.
+ const next = sub.active ? schedule.nextRenewal(sub.startDate, sub.freq, schedule.addDays(today, 1)) : null;
+ const all = history.charges(sub, next || today, today).reverse();
+ const visible = expanded ? all : all.slice(0, SHOWN);
+
+ const head = h('div', { class: 'history-head' },
+ logo(sub),
+ h('div', null,
+ h('p', { class: 'label', text: t('history.paidSoFar') }),
+ h('p', { class: 'history-total', text: i18n.fmtMoney(sum.total, sub.currency) }),
+ h('p', {
+ class: 'hint',
+ text: sum.count
+ ? i18n.tp('history.count', sum.count, { date: i18n.fmtDate(sum.since) })
+ : t('history.none', { date: i18n.fmtDate(schedule.nextRenewal(sub.startDate, sub.freq) || today) }),
+ })));
+
+ const rows = visible.map((c) => {
+ const disabled = c.status === 'upcoming';
+ const amount = c.status === 'skipped' ? '—' : i18n.fmtMoney(c.amount, c.currency);
+ const showExpected = c.status === 'paid' && c.amount !== c.expected;
+ return h('li', null, h('button', {
+ type: 'button',
+ class: `charge-row is-${c.status}`,
+ disabled,
+ 'aria-label': `${i18n.fmtDate(c.date)}, ${amount}, ${t(`history.status.${c.status}`)}`,
+ on: { click: () => openCharge(sub, c, changed) },
+ },
+ h('span', { class: 'charge-date', text: i18n.fmtDate(c.date, { day: 'numeric', month: 'short', year: 'numeric' }) }),
+ h('span', { class: `chip-status st-${c.status}`, text: t(`history.status.${c.status}`) }),
+ h('span', { class: 'charge-amount' },
+ h('span', { text: amount }),
+ showExpected ? h('span', { class: 'per', text: t('history.expected', { amount: i18n.fmtMoney(c.expected, c.currency) }) }) : null)));
+ });
+
+ const prices = (sub.priceHistory || []).length > 1
+ ? h('section', { class: 'set-group' },
+ h('h3', { text: t('history.prices') }),
+ h('ul', { class: 'set-card price-list' },
+ [...sub.priceHistory].reverse().map((e) => h('li', { class: 'set-row' },
+ h('span', { class: 'set-text', text: i18n.fmtDate(schedule.parseISO(e.from)) }),
+ h('span', { class: 'price', text: i18n.fmtMoney(e.price, sub.currency) })))))
+ : null;
+
+ body.replaceChildren();
+ append(body, [
+ head,
+ h('p', { class: 'hint history-hint', text: t('history.hint') }),
+ all.length ? h('section', { class: 'set-group' },
+ h('h3', { text: t('history.charges') }),
+ h('ul', { class: 'set-card charge-list' }, rows),
+ !expanded && all.length > SHOWN ? h('button', {
+ type: 'button',
+ class: 'btn btn-ghost btn-block show-all',
+ text: t('history.showAll', { n: all.length }),
+ on: { click: () => { expanded = true; draw(); } },
+ }) : null) : null,
+ prices,
+ ]);
+ }
+ draw();
+ }
+
+ function openCharge(sub, charge, onChange) {
+ const override = sub.charges && sub.charges[charge.iso];
+ const amount = h('input', {
+ class: 'input input-price',
+ type: 'text',
+ inputmode: 'decimal',
+ autocomplete: 'off',
+ value: String(charge.status === 'skipped' ? charge.expected : charge.amount)
+ .replace('.', i18n.lang === 'it' ? ',' : '.'),
+ });
+ const err = h('p', { class: 'error', 'aria-live': 'polite' });
+ const confirmBtn = h('button', { class: 'btn btn-primary btn-block', type: 'button', text: t('charge.confirm') });
+ const skipBtn = h('button', { class: 'btn btn-ghost btn-block', type: 'button', text: t('charge.skip') });
+ const resetBtn = override
+ ? h('button', { class: 'btn btn-ghost btn-block', type: 'button', text: t('charge.reset') }) : null;
+
+ const s = sheet({
+ title: t('charge.title', { date: i18n.fmtDate(charge.date, { day: 'numeric', month: 'long', year: 'numeric' }) }),
+ body: h('div', { class: 'form' },
+ h('div', { class: 'field' },
+ h('label', { for: 'f-charge', text: t('charge.amount') }),
+ h('div', { class: 'price-row' },
+ Object.assign(amount, { id: 'f-charge' }),
+ h('span', { class: 'input input-currency currency-static', text: sub.currency })),
+ err),
+ h('p', { class: 'hint', text: t('history.expected', { amount: i18n.fmtMoney(charge.expected, sub.currency) }) })),
+ footer: h('div', { class: 'form-actions' }, confirmBtn, skipBtn, resetBtn),
+ });
+
+ async function update(entry) {
+ const fresh = state.subs.find((x) => x.id === sub.id) || sub;
+ const charges = { ...(fresh.charges || {}) };
+ if (entry) charges[charge.iso] = entry;
+ else delete charges[charge.iso];
+ await saveSub({ ...fresh, charges });
+ haptic(12);
+ s.close('saved');
+ toast(t('charge.saved'));
+ onChange();
+ }
+
+ confirmBtn.addEventListener('click', () => {
+ const v = parsePrice(amount.value);
+ if (!Number.isFinite(v) || v < 0) {
+ err.textContent = t('form.errPrice');
+ amount.focus();
+ return;
+ }
+ update({ status: 'paid', amount: Math.round(v * 100) / 100 });
+ });
+ skipBtn.addEventListener('click', () => update({ status: 'skipped' }));
+ if (resetBtn) resetBtn.addEventListener('click', () => update(null));
+ }
+
+ // ---------- Actual spending chart ----------
+
+ function renderSpend() {
+ const host = $('spend');
+ const today = schedule.today();
+ const buckets = history.monthly(state.subs, 12, today);
+ const curs = new Set(state.subs.map((x) => x.currency));
+ const main = curs.size === 1 ? [...curs][0] : state.settings.currency;
+ const excluded = new Set();
+ const values = buckets.map((b) => {
+ let v = 0;
+ for (const [cur, amount] of b.byCur) {
+ const c = cur === main ? amount : convert(amount, cur);
+ if (c == null) excluded.add(cur);
+ else v += c;
+ }
+ return v;
+ });
+ const total = values.reduce((a, b) => a + b, 0);
+ const ytd = values.reduce((a, v, i) => a + (buckets[i].date.getFullYear() === today.getFullYear() ? v : 0), 0);
+
+ if (!total && !excluded.size) {
+ host.replaceChildren(h('p', { class: 'muted', text: t('spend.none') }));
+ return;
+ }
+
+ const max = Math.max(...values, 0);
+ const label = (i) => `${i18n.fmtDate(buckets[i].date, { month: 'long', year: 'numeric' })} · ${i18n.fmtMoney(values[i], main)}`;
+ const readout = h('p', { class: 'spend-readout', 'aria-live': 'polite', text: label(values.length - 1) });
+ const narrow = new Intl.DateTimeFormat(i18n.lang, { month: 'narrow' });
+
+ const bars = h('div', { class: 'bars', role: 'group', 'aria-label': t('spend.chart') },
+ values.map((v, i) => {
+ const bar = h('button', {
+ type: 'button',
+ class: `bar${i === values.length - 1 ? ' is-current' : ''}`,
+ 'aria-label': label(i),
+ },
+ h('span', {
+ class: `bar-fill${v > 0 ? '' : ' is-zero'}`,
+ style: { '--h': `${max ? (v / max) * 100 : 0}%` },
+ }),
+ h('span', { class: 'bar-label', 'aria-hidden': 'true', text: narrow.format(buckets[i].date) }));
+ const show = () => {
+ readout.textContent = label(i);
+ for (const b of bars.children) b.classList.toggle('is-active', b === bar);
+ };
+ bar.addEventListener('pointerenter', show);
+ bar.addEventListener('focus', show);
+ bar.addEventListener('click', () => { show(); haptic(); });
+ return bar;
+ }));
+ bars.addEventListener('pointerleave', () => {
+ readout.textContent = label(values.length - 1);
+ for (const b of bars.children) b.classList.remove('is-active');
+ });
+
+ host.replaceChildren();
+ append(host, [
+ h('div', { class: 'spend-stats' },
+ h('div', null,
+ h('p', { class: 'label', text: t('spend.last12') }),
+ h('p', { class: 'spend-value', text: i18n.fmtMoney(total, main) })),
+ h('div', null,
+ h('p', { class: 'label', text: t('spend.ytd') }),
+ h('p', { class: 'spend-value', text: i18n.fmtMoney(ytd, main) }))),
+ readout,
+ bars,
+ excluded.size ? h('p', { class: 'hint spend-note', text: t('spend.only', { cur: main }) }) : null,
+ ]);
+ }
+
function afterSave(editing) {
const canAsk = 'Notification' in g && reminders.permission() === 'default' && !state.settings.notifications;
if (!editing && canAsk && state.subs.length === 1) {
@@ -640,7 +930,10 @@
runReminders();
}
- async function removeSub(sub, s) {
+ async function removeSub(original, s) {
+ // The history sheet may have updated the record since the form opened:
+ // keep the stored copy so Undo restores confirmed charges too.
+ const sub = state.subs.find((x) => x.id === original.id) || original;
const ok = await ui.confirm(t('form.confirmDelete', { name: sub.name }), t('form.delete'));
if (!ok) return;
await db.remove(sub.id);
diff --git a/js/core/db.js b/js/core/db.js
index 391b8c5..2a7d928 100644
--- a/js/core/db.js
+++ b/js/core/db.js
@@ -114,12 +114,18 @@
const now = Date.now();
const id = typeof input.id === 'string' && /^[\w-]{8,64}$/.test(input.id)
? input.id : uuid();
+ const active = input.active !== false;
+ const priceHistory = sanitizePriceHistory(input.priceHistory, startDate, price);
return {
id,
catalogId,
name,
- price,
+ // The latest entry of the price history is the current price.
+ price: priceHistory[priceHistory.length - 1].price,
+ priceHistory,
+ charges: sanitizeCharges(input.charges),
+ pausedAt: !active && schedule.parseISO(input.pausedAt) ? input.pausedAt : null,
currency,
freq,
startDate,
@@ -127,12 +133,45 @@
color,
reminder, // -1 = none, 0 = same day, n = days before
notes: str(input.notes, 1000),
- active: input.active !== false,
+ active,
createdAt: Number.isFinite(input.createdAt) ? input.createdAt : now,
updatedAt: now,
};
}
+ function money(v) {
+ const n = Math.round(Number(v) * 100) / 100;
+ return Number.isFinite(n) && n >= 0 && n <= 1e7 ? n : null;
+ }
+
+ const ISO = /^\d{4}-\d{2}-\d{2}$/;
+
+ function sanitizePriceHistory(input, startDate, price) {
+ const byDate = new Map();
+ if (Array.isArray(input)) {
+ for (const e of input.slice(0, 200)) {
+ const p = e && money(e.price);
+ if (p != null && ISO.test(e.from) && ST.schedule.parseISO(e.from)) byDate.set(e.from, p);
+ }
+ }
+ if (!byDate.size) return [{ from: startDate, price }];
+ return [...byDate].sort(([a], [b]) => (a < b ? -1 : 1)).map(([from, p]) => ({ from, price: p }));
+ }
+
+ function sanitizeCharges(input) {
+ const out = {};
+ if (!input || typeof input !== 'object') return out;
+ for (const [iso, c] of Object.entries(input).slice(0, 5000)) {
+ if (!ISO.test(iso) || !ST.schedule.parseISO(iso) || !c) continue;
+ if (c.status === 'skipped') out[iso] = { status: 'skipped' };
+ else if (c.status === 'paid') {
+ const a = money(c.amount);
+ out[iso] = a == null ? { status: 'paid' } : { status: 'paid', amount: a };
+ }
+ }
+ return out;
+ }
+
function uuid() {
if (g.crypto && g.crypto.randomUUID) return g.crypto.randomUUID();
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
diff --git a/js/core/history.js b/js/core/history.js
new file mode 100644
index 0000000..5246a95
--- /dev/null
+++ b/js/core/history.js
@@ -0,0 +1,138 @@
+/*
+ * Payment history.
+ *
+ * Past charges are derived from the billing schedule (start date + frequency)
+ * and the subscription's price history. The user can override any single
+ * charge: confirm the amount actually paid, or mark it as not charged.
+ *
+ * Data kept on each subscription (see db.sanitize):
+ * priceHistory [{ from: 'YYYY-MM-DD', price }] sorted by `from`; a price
+ * applies to charges on or after its date. Charges before the
+ * first entry use the first price.
+ * charges { 'YYYY-MM-DD': { status: 'paid' | 'skipped', amount? } }
+ * pausedAt 'YYYY-MM-DD' | null - no charges after this date.
+ */
+(function (g) {
+ 'use strict';
+ const ST = (g.ST = g.ST || {});
+
+ function priceAt(sub, iso) {
+ const hist = sub.priceHistory;
+ if (!hist || !hist.length) return sub.price;
+ let price = hist[0].price;
+ for (const entry of hist) {
+ if (entry.from <= iso) price = entry.price;
+ else break;
+ }
+ return price;
+ }
+
+ /**
+ * All charges of a subscription from its start up to `until` (inclusive).
+ * Each item: { date, iso, amount, currency, status }
+ * status: 'assumed' (computed), 'paid' (confirmed), 'skipped', 'upcoming'.
+ */
+ function charges(sub, until, today) {
+ const { schedule } = ST;
+ const start = schedule.parseISO(sub.startDate);
+ if (!start) return [];
+ const ref = today || schedule.today();
+ const todayISO = schedule.toISO(ref);
+ let end = until || ref;
+ const paused = sub.pausedAt && schedule.parseISO(sub.pausedAt);
+ if (paused && paused < end) end = paused;
+
+ const out = [];
+ for (const date of schedule.occurrencesBetween(sub.startDate, sub.freq, start, end)) {
+ const iso = schedule.toISO(date);
+ const override = sub.charges && sub.charges[iso];
+ const base = priceAt(sub, iso);
+ let status = iso > todayISO ? 'upcoming' : 'assumed';
+ let amount = base;
+ if (override && status !== 'upcoming') {
+ status = override.status;
+ amount = override.status === 'skipped' ? 0
+ : (Number.isFinite(override.amount) ? override.amount : base);
+ }
+ out.push({ date, iso, amount, expected: base, currency: sub.currency, status });
+ }
+ return out;
+ }
+
+ /** Charges actually counted as spent (paid or assumed, not upcoming/skipped). */
+ function isSpent(c) {
+ return c.status === 'paid' || c.status === 'assumed';
+ }
+
+ /** { total, count, since } for one subscription up to today. */
+ function summary(sub, today) {
+ const list = charges(sub, today, today).filter(isSpent);
+ return {
+ total: list.reduce((s, c) => s + c.amount, 0),
+ count: list.length,
+ since: list.length ? list[0].date : null,
+ };
+ }
+
+ /**
+ * Spending per calendar month for the `months` months ending with the
+ * current one. Returns [{ key: 'YYYY-MM', date, byCur: Map }].
+ */
+ function monthly(subs, months, today) {
+ const { schedule } = ST;
+ const ref = today || schedule.today();
+ const buckets = [];
+ const index = new Map();
+ for (let i = months - 1; i >= 0; i--) {
+ const d = new Date(ref.getFullYear(), ref.getMonth() - i, 1);
+ const key = schedule.toISO(d).slice(0, 7);
+ const b = { key, date: d, byCur: new Map() };
+ buckets.push(b);
+ index.set(key, b);
+ }
+ for (const sub of subs) {
+ for (const c of charges(sub, ref, ref)) {
+ if (!isSpent(c)) continue;
+ const b = index.get(c.iso.slice(0, 7));
+ if (b) b.byCur.set(c.currency, (b.byCur.get(c.currency) || 0) + c.amount);
+ }
+ }
+ return buckets;
+ }
+
+ /**
+ * New price history after changing the price.
+ * mode: 'all' - correct every past charge (single entry from the start);
+ * an ISO date - the new price applies from that date onwards.
+ */
+ function withPrice(sub, price, mode) {
+ const hist = (sub.priceHistory && sub.priceHistory.length)
+ ? sub.priceHistory : [{ from: sub.startDate, price: sub.price }];
+ if (mode === 'all') return [{ from: sub.startDate, price }];
+ const kept = hist.filter((e) => e.from < mode);
+ if (!kept.length) return [{ from: sub.startDate, price }];
+ if (kept[kept.length - 1].price === price) return kept;
+ return [...kept, { from: mode, price }];
+ }
+
+ /**
+ * Charges to mark as skipped when a paused subscription is resumed:
+ * every billing date after the pause, up to and excluding today.
+ */
+ function skippedWhilePaused(sub, today) {
+ const { schedule } = ST;
+ const paused = sub.pausedAt && schedule.parseISO(sub.pausedAt);
+ if (!paused) return {};
+ const ref = today || schedule.today();
+ const out = {};
+ const from = schedule.addDays(paused, 1);
+ const to = schedule.addDays(ref, -1);
+ if (from > to) return out;
+ for (const d of schedule.occurrencesBetween(sub.startDate, sub.freq, from, to)) {
+ out[schedule.toISO(d)] = { status: 'skipped' };
+ }
+ return out;
+ }
+
+ ST.history = { priceAt, charges, isSpent, summary, monthly, withPrice, skippedWhilePaused };
+})(typeof self !== 'undefined' ? self : globalThis);
diff --git a/js/core/i18n.js b/js/core/i18n.js
index e30e38c..475904e 100644
--- a/js/core/i18n.js
+++ b/js/core/i18n.js
@@ -180,6 +180,37 @@
'notif.inDays': 'in {n} days',
'notif.testTitle': 'Notifications work!',
'notif.testBody': 'You will be reminded before your subscriptions renew.',
+ 'history.title': 'Payment history',
+ 'history.open': 'Payment history',
+ 'history.paidSoFar': 'Paid so far',
+ 'history.count.one': '{n} charge since {date}',
+ 'history.count.other': '{n} charges since {date}',
+ 'history.none': 'No charges yet: the first one is on {date}.',
+ 'history.hint': 'Past charges are calculated from the start date and price. Tap a charge to confirm the amount you actually paid, or mark it as not charged.',
+ 'history.charges': 'Charges',
+ 'history.prices': 'Price changes',
+ 'history.showAll': 'Show all ({n})',
+ 'history.status.assumed': 'Calculated',
+ 'history.status.paid': 'Confirmed',
+ 'history.status.skipped': 'Not charged',
+ 'history.status.upcoming': 'Upcoming',
+ 'history.expected': 'expected {amount}',
+ 'charge.title': 'Charge of {date}',
+ 'charge.amount': 'Amount charged',
+ 'charge.confirm': 'Confirm payment',
+ 'charge.skip': 'It was not charged',
+ 'charge.reset': 'Back to automatic',
+ 'charge.saved': 'Charge updated',
+ 'price.apply': 'Apply the new price',
+ 'price.fromNext': 'From the next renewal ({date})',
+ 'price.fromLast': 'From the last charge ({date})',
+ 'price.all': 'To the whole history (correction)',
+ 'spend.title': 'Actual spending',
+ 'spend.last12': 'Last 12 months',
+ 'spend.ytd': 'This year',
+ 'spend.chart': 'Spending per month, last 12 months',
+ 'spend.only': 'Only {cur} charges are included. Set exchange rates in Settings to include other currencies.',
+ 'spend.none': 'No charges in the last 12 months.',
},
it: {
@@ -352,6 +383,37 @@
'notif.inDays': 'tra {n} giorni',
'notif.testTitle': 'Le notifiche funzionano!',
'notif.testBody': 'Riceverai un avviso prima del rinnovo dei tuoi abbonamenti.',
+ 'history.title': 'Storico pagamenti',
+ 'history.open': 'Storico pagamenti',
+ 'history.paidSoFar': 'Pagato finora',
+ 'history.count.one': '{n} addebito dal {date}',
+ 'history.count.other': '{n} addebiti dal {date}',
+ 'history.none': 'Ancora nessun addebito: il primo è il {date}.',
+ 'history.hint': 'Gli addebiti passati sono calcolati dalla data di inizio e dal prezzo. Tocca un addebito per confermare l’importo pagato davvero, o segnarlo come non addebitato.',
+ 'history.charges': 'Addebiti',
+ 'history.prices': 'Variazioni di prezzo',
+ 'history.showAll': 'Mostra tutti ({n})',
+ 'history.status.assumed': 'Calcolato',
+ 'history.status.paid': 'Confermato',
+ 'history.status.skipped': 'Non addebitato',
+ 'history.status.upcoming': 'In arrivo',
+ 'history.expected': 'previsto {amount}',
+ 'charge.title': 'Addebito del {date}',
+ 'charge.amount': 'Importo addebitato',
+ 'charge.confirm': 'Conferma pagamento',
+ 'charge.skip': 'Non è stato addebitato',
+ 'charge.reset': 'Torna al calcolo automatico',
+ 'charge.saved': 'Addebito aggiornato',
+ 'price.apply': 'Applica il nuovo prezzo',
+ 'price.fromNext': 'Dal prossimo rinnovo ({date})',
+ 'price.fromLast': 'Dall’ultimo addebito ({date})',
+ 'price.all': 'A tutto lo storico (correzione)',
+ 'spend.title': 'Spesa effettiva',
+ 'spend.last12': 'Ultimi 12 mesi',
+ 'spend.ytd': 'Da inizio anno',
+ 'spend.chart': 'Spesa per mese, ultimi 12 mesi',
+ 'spend.only': 'Sono inclusi solo gli addebiti in {cur}. Imposta i tassi di cambio nelle Impostazioni per includere le altre valute.',
+ 'spend.none': 'Nessun addebito negli ultimi 12 mesi.',
},
};
diff --git a/js/core/reminders.js b/js/core/reminders.js
index 5407358..e2503c9 100644
--- a/js/core/reminders.js
+++ b/js/core/reminders.js
@@ -29,6 +29,10 @@
return out;
}
+ function price(item) {
+ return ST.history ? ST.history.priceAt(item.sub, ST.schedule.toISO(item.next)) : item.sub.price;
+ }
+
function text(item) {
const { t, fmtMoney, fmtDate } = ST.i18n;
const when = item.days === 0 ? t('notif.today')
@@ -36,7 +40,7 @@
: t('notif.inDays', { n: item.days });
return {
title: t('notif.title', { name: item.sub.name, when }),
- body: `${fmtMoney(item.sub.price, item.sub.currency)} · ${fmtDate(item.next, { weekday: 'long', day: 'numeric', month: 'long' })}`,
+ body: `${fmtMoney(price(item), item.sub.currency)} · ${fmtDate(item.next, { weekday: 'long', day: 'numeric', month: 'long' })}`,
};
}
diff --git a/js/core/version.js b/js/core/version.js
index bb71623..ab618a3 100644
--- a/js/core/version.js
+++ b/js/core/version.js
@@ -2,6 +2,6 @@
(function (g) {
'use strict';
const ST = (g.ST = g.ST || {});
- ST.VERSION = '1.0.2';
+ ST.VERSION = '1.1.0';
ST.REPO_URL = 'https://github.com/lestolo/subscription-tracker';
})(typeof self !== 'undefined' ? self : globalThis);
diff --git a/sw.js b/sw.js
index fb3173e..a614e5c 100644
--- a/sw.js
+++ b/sw.js
@@ -9,6 +9,7 @@ importScripts(
'js/core/schedule.js',
'js/core/i18n.js',
'js/core/db.js',
+ 'js/core/history.js',
'js/core/reminders.js',
);
@@ -26,6 +27,7 @@ const ASSETS = [
'js/core/db.js',
'js/core/reminders.js',
'js/core/ics.js',
+ 'js/core/history.js',
'js/ui.js',
'js/install.js',
'js/app.js',
diff --git a/tests/helpers.js b/tests/helpers.js
index fbee8ef..2fdcccb 100644
--- a/tests/helpers.js
+++ b/tests/helpers.js
@@ -7,6 +7,7 @@ await import('../js/core/i18n.js');
await import('../js/core/db.js');
await import('../js/core/reminders.js');
await import('../js/core/ics.js');
+await import('../js/core/history.js');
export const ST = globalThis.ST;
export const d = (s) => ST.schedule.parseISO(s);
diff --git a/tests/history.test.js b/tests/history.test.js
new file mode 100644
index 0000000..03f7680
--- /dev/null
+++ b/tests/history.test.js
@@ -0,0 +1,94 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { ST, d } from './helpers.js';
+
+const { history, db } = ST;
+
+function sub(extra) {
+ return db.sanitize({
+ name: 'Netflix', price: 10, currency: 'EUR', startDate: '2026-01-31',
+ freq: { every: 1, unit: 'month' }, ...extra,
+ });
+}
+
+test('legacy subscription gets a single-entry price history', () => {
+ const s = sub();
+ assert.deepEqual(s.priceHistory, [{ from: '2026-01-31', price: 10 }]);
+ assert.deepEqual(s.charges, {});
+ assert.equal(s.pausedAt, null);
+});
+
+test('past charges are derived from the schedule, upcoming ones are flagged', () => {
+ const list = history.charges(sub(), d('2026-06-30'), d('2026-04-15'));
+ assert.deepEqual(list.map((c) => c.iso),
+ ['2026-01-31', '2026-02-28', '2026-03-31', '2026-04-30', '2026-05-31', '2026-06-30']);
+ assert.deepEqual(list.map((c) => c.status),
+ ['assumed', 'assumed', 'assumed', 'upcoming', 'upcoming', 'upcoming']);
+ const sum = history.summary(sub(), d('2026-04-15'));
+ assert.equal(sum.total, 30);
+ assert.equal(sum.count, 3);
+ assert.equal(history.summary(sub({ startDate: '2026-12-01' }), d('2026-04-15')).count, 0);
+});
+
+test('price changes only apply from their date', () => {
+ const s = sub({ priceHistory: [{ from: '2026-01-31', price: 10 }, { from: '2026-03-31', price: 12 }] });
+ assert.equal(s.price, 12, 'current price is the latest entry');
+ assert.equal(history.priceAt(s, '2026-02-28'), 10);
+ assert.equal(history.priceAt(s, '2026-03-31'), 12);
+ assert.equal(history.priceAt(s, '2025-01-01'), 10, 'before the first entry uses the first price');
+ assert.equal(history.summary(s, d('2026-04-15')).total, 32);
+});
+
+test('withPrice: from a date, or correcting the whole history', () => {
+ const s = sub();
+ const next = history.withPrice(s, 13, '2026-04-30');
+ assert.deepEqual(next, [{ from: '2026-01-31', price: 10 }, { from: '2026-04-30', price: 13 }]);
+ const s2 = sub({ priceHistory: next });
+ // A later change replaces entries on/after its date.
+ assert.deepEqual(history.withPrice(s2, 11, '2026-03-31'),
+ [{ from: '2026-01-31', price: 10 }, { from: '2026-03-31', price: 11 }]);
+ assert.deepEqual(history.withPrice(s2, 9, 'all'), [{ from: '2026-01-31', price: 9 }]);
+ // Same price as before the date: no new entry.
+ assert.deepEqual(history.withPrice(s, 10, '2026-04-30'), [{ from: '2026-01-31', price: 10 }]);
+});
+
+test('confirmed and skipped charges override the computed amount', () => {
+ const s = sub({ charges: {
+ '2026-02-28': { status: 'paid', amount: 10.5 },
+ '2026-03-31': { status: 'skipped' },
+ '2026-05-31': { status: 'paid', amount: 99 }, // future: ignored
+ } });
+ const list = history.charges(s, d('2026-05-31'), d('2026-04-15'));
+ assert.deepEqual(list.map((c) => [c.status, c.amount]),
+ [['assumed', 10], ['paid', 10.5], ['skipped', 0], ['upcoming', 10], ['upcoming', 10]]);
+ assert.equal(history.summary(s, d('2026-04-15')).total, 20.5);
+ assert.equal(history.summary(s, d('2026-04-15')).count, 2);
+});
+
+test('paused subscriptions stop charging; resuming skips the gap', () => {
+ const s = sub({ active: false, pausedAt: '2026-02-15' });
+ assert.equal(history.summary(s, d('2026-06-01')).count, 1);
+ const gap = history.skippedWhilePaused(s, d('2026-04-30'));
+ assert.deepEqual(Object.keys(gap), ['2026-02-28', '2026-03-31']);
+ // pausedAt is dropped when active.
+ assert.equal(sub({ active: true, pausedAt: '2026-02-15' }).pausedAt, null);
+});
+
+test('monthly buckets per currency for the last N months', () => {
+ const a = sub();
+ const b = db.sanitize({ name: 'X', price: 120, currency: 'USD', startDate: '2025-03-10', freq: { every: 1, unit: 'year' } });
+ const buckets = history.monthly([a, b], 4, d('2026-04-15'));
+ assert.deepEqual(buckets.map((x) => x.key), ['2026-01', '2026-02', '2026-03', '2026-04']);
+ assert.equal(buckets[0].byCur.get('EUR'), 10);
+ assert.equal(buckets[2].byCur.get('USD'), 120);
+ assert.equal(buckets[3].byCur.size, 0, 'April charge is upcoming (30th)');
+});
+
+test('sanitize rejects malformed history and charges', () => {
+ const s = sub({
+ priceHistory: [{ from: 'nope', price: 5 }, { from: '2026-02-30', price: 5 }, { from: '2026-03-01', price: -1 }],
+ charges: { '__proto__': { status: 'paid' }, '2026-02-28': { status: 'evil' }, '2026-03-31': { status: 'paid', amount: 'x' } },
+ });
+ assert.deepEqual(s.priceHistory, [{ from: '2026-01-31', price: 10 }]);
+ assert.deepEqual(s.charges, { '2026-03-31': { status: 'paid' } });
+});