diff --git a/app/controllers/savings_goals_controller.rb b/app/controllers/savings_goals_controller.rb index 466d83d62..d8590983a 100644 --- a/app/controllers/savings_goals_controller.rb +++ b/app/controllers/savings_goals_controller.rb @@ -185,15 +185,45 @@ class SavingsGoalsController < ApplicationController end months_since_start = ((Date.current.year - goal.created_at.year) * 12 + (Date.current.month - goal.created_at.month)).clamp(0, 1200) sub_started = t("savings_goals.show.stats.months_ago", count: months_since_start) + linked_balance = goal.linked_accounts.sum { |a| a.balance.to_d } + sub_linked = t("savings_goals.show.stats.n_accounts", count: goal.linked_accounts.size) + + summary = projection_summary(goal, avg) + { avg_monthly: avg, avg_monthly_sub: sub_avg, contributions_count: goal.savings_contributions.count, monthly_target_sub: sub_target, - started_sub: sub_started + started_sub: sub_started, + linked_balance: linked_balance, + linked_balance_sub: sub_linked, + projection_summary: summary } end + def projection_summary(goal, avg_monthly) + currency = goal.currency + money = ->(amount) { Money.new(amount, currency).format } + + if goal.completed? || goal.progress_percent >= 100 + t("savings_goals.show.projection.reached") + elsif goal.target_date.nil? + t("savings_goals.show.projection.no_target_date") + elsif goal.monthly_target_amount && avg_monthly < goal.monthly_target_amount + t("savings_goals.show.projection.behind", + current: money.call(avg_monthly), + required: money.call(goal.monthly_target_amount)) + elsif avg_monthly.positive? + months_to_target = (goal.remaining_amount.to_d / avg_monthly).ceil + projected_date = Date.current >> months_to_target.to_i + t("savings_goals.show.projection.on_track", + date: projected_date.strftime("%b %Y")) + else + t("savings_goals.show.projection.no_pace") + end + end + def perform_transition!(event) if @savings_goal.aasm.may_fire_event?(event) @savings_goal.public_send("#{event}!") diff --git a/app/javascript/controllers/savings_goal_projection_chart_controller.js b/app/javascript/controllers/savings_goal_projection_chart_controller.js new file mode 100644 index 000000000..b898d7916 --- /dev/null +++ b/app/javascript/controllers/savings_goal_projection_chart_controller.js @@ -0,0 +1,200 @@ +import { Controller } from "@hotwired/stimulus"; +import * as d3 from "d3"; + +// Projection chart for a savings goal. Renders: +// - Saved area + line from goal creation → today (solid) +// - Dashed projection line from today → target date (yellow if behind, +// green if on track) +// - Horizontal dashed target line with label +// - Today marker (vertical line + dot) +// +// Data shape passed via `data-savings-goal-projection-chart-data-value` +// matches SavingsGoal#projection_payload. +export default class extends Controller { + static values = { data: Object }; + + connect() { + this._draw(); + this._resize = this._draw.bind(this); + window.addEventListener("resize", this._resize); + } + + disconnect() { + window.removeEventListener("resize", this._resize); + } + + _draw() { + const root = this.element; + root.innerHTML = ""; + + const data = this.dataValue || {}; + const width = root.clientWidth || 720; + const height = root.clientHeight || 240; + if (width <= 0 || height <= 0) return; + + const margin = { top: 28, right: 24, bottom: 28, left: 16 }; + const innerWidth = width - margin.left - margin.right; + const innerHeight = height - margin.top - margin.bottom; + + const start = new Date(data.start_date); + const today = new Date(data.today); + const target = data.target_date ? new Date(data.target_date) : null; + const targetAmount = data.target_amount || 0; + const currentAmount = data.current_amount || 0; + const avgMonthly = data.avg_monthly || 0; + + const endDate = target || new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000); + + const savedSeries = [{ date: start, value: 0 }].concat( + (data.saved_series || []).map((p) => ({ date: new Date(p.date), value: p.value })), + ); + if (savedSeries[savedSeries.length - 1].date < today) { + savedSeries.push({ date: today, value: currentAmount }); + } + + const projectionEnd = target + ? Math.max(currentAmount, currentAmount + avgMonthly * Math.max(0, this._monthsBetween(today, target))) + : currentAmount; + const projectionSeries = target + ? [ + { date: today, value: currentAmount }, + { date: target, value: projectionEnd }, + ] + : []; + + const yMax = Math.max(targetAmount * 1.05, projectionEnd, currentAmount, 1); + + const x = d3.scaleTime().domain([start, endDate]).range([margin.left, margin.left + innerWidth]); + const y = d3.scaleLinear().domain([0, yMax]).range([margin.top + innerHeight, margin.top]); + + const svg = d3 + .select(root) + .append("svg") + .attr("width", width) + .attr("height", height) + .attr("viewBox", `0 0 ${width} ${height}`) + .attr("preserveAspectRatio", "none"); + + const defs = svg.append("defs"); + const gradient = defs + .append("linearGradient") + .attr("id", `saved-fill-${this._id()}`) + .attr("x1", 0).attr("y1", 0).attr("x2", 0).attr("y2", 1); + gradient.append("stop").attr("offset", "0%").attr("stop-color", "var(--text-primary)").attr("stop-opacity", 0.10); + gradient.append("stop").attr("offset", "100%").attr("stop-color", "var(--text-primary)").attr("stop-opacity", 0); + + if (targetAmount > 0) { + svg + .append("line") + .attr("x1", margin.left) + .attr("x2", margin.left + innerWidth) + .attr("y1", y(targetAmount)) + .attr("y2", y(targetAmount)) + .attr("stroke", "var(--border-strong)") + .attr("stroke-width", 1) + .attr("stroke-dasharray", "3 3"); + + svg + .append("text") + .attr("x", margin.left + innerWidth - 4) + .attr("y", y(targetAmount) - 6) + .attr("text-anchor", "end") + .attr("font-size", 10) + .attr("fill", "var(--text-secondary)") + .text(`Target · ${this._fmtMoney(targetAmount, data.currency)}`); + } + + const area = d3 + .area() + .x((d) => x(d.date)) + .y0(margin.top + innerHeight) + .y1((d) => y(d.value)) + .curve(d3.curveMonotoneX); + + const line = d3 + .line() + .x((d) => x(d.date)) + .y((d) => y(d.value)) + .curve(d3.curveMonotoneX); + + svg + .append("path") + .datum(savedSeries) + .attr("fill", `url(#saved-fill-${this._id()})`) + .attr("d", area); + + svg + .append("path") + .datum(savedSeries) + .attr("fill", "none") + .attr("stroke", "var(--text-primary)") + .attr("stroke-width", 2) + .attr("stroke-linejoin", "round") + .attr("stroke-linecap", "round") + .attr("d", line); + + if (projectionSeries.length) { + const willHit = projectionEnd >= targetAmount; + svg + .append("path") + .datum(projectionSeries) + .attr("fill", "none") + .attr("stroke", willHit ? "var(--color-green-600)" : "var(--color-yellow-600)") + .attr("stroke-width", 2) + .attr("stroke-linecap", "round") + .attr("stroke-dasharray", "4 4") + .attr("d", line); + } + + svg + .append("line") + .attr("x1", x(today)) + .attr("x2", x(today)) + .attr("y1", margin.top) + .attr("y2", margin.top + innerHeight) + .attr("stroke", "var(--border-subdued)") + .attr("stroke-width", 1) + .attr("stroke-dasharray", "2 4"); + + svg + .append("circle") + .attr("cx", x(today)) + .attr("cy", y(currentAmount)) + .attr("r", 4) + .attr("fill", "var(--text-primary)") + .attr("stroke", "var(--bg-container)") + .attr("stroke-width", 2); + + const tickFmt = d3.timeFormat("%b %y"); + const tickCount = Math.min(5, Math.max(2, Math.round(innerWidth / 110))); + const ticks = x.ticks(tickCount); + svg + .append("g") + .selectAll("text") + .data(ticks) + .enter() + .append("text") + .attr("x", (d) => x(d)) + .attr("y", height - 8) + .attr("text-anchor", "middle") + .attr("font-size", 10) + .attr("fill", "var(--text-subdued)") + .text((d) => tickFmt(d)); + } + + _monthsBetween(a, b) { + return (b - a) / (1000 * 60 * 60 * 24 * 30.44); + } + + _fmtMoney(amount, currency) { + const symbol = currency === "EUR" ? "€" : currency === "GBP" ? "£" : "$"; + return `${symbol}${Math.round(amount).toLocaleString()}`; + } + + _id() { + if (!this._cachedId) { + this._cachedId = Math.random().toString(36).slice(2, 8); + } + return this._cachedId; + } +} diff --git a/app/javascript/controllers/savings_goal_stepper_controller.js b/app/javascript/controllers/savings_goal_stepper_controller.js index 64dd380b4..796ee058f 100644 --- a/app/javascript/controllers/savings_goal_stepper_controller.js +++ b/app/javascript/controllers/savings_goal_stepper_controller.js @@ -3,46 +3,86 @@ import { Controller } from "@hotwired/stimulus"; // 2-step modal stepper for creating a savings goal. // // Single