The personal finance app for everyone (by everyone)
Ruby
require "securerandom"
class Demo::Generator
# Alias the canonical sentinel from Subscription so callers that already
# reference Demo::Generator::DEMO_STRIPE_SUBSCRIPTION_ID keep working.
DEMO_STRIPE_SUBSCRIPTION_ID = Subscription::DEMO_STRIPE_ID
# Organic Maps' published donation addresses (organicmaps.app/donate): real,
# public and modest. Every sync re-reads a wallet from its chain, so a made-up
# address would drop to zero on the demo user's first sync.
ONCHAIN_DEMO_WALLETS = [
{ chain: "bitcoin", address: "bc1qxnn9j9z5xywqz5sdqxaq327vw0x22nhsxc67ld", tokens: [] },
{ chain: "ethereum", address: "0xC36A638DD2274BDe6097DFD62B3EB5Aa8A67Ec54", tokens: [
{ symbol: "USDC", name: "USD Coin", decimals: 6, contract: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" },
{ symbol: "USDT", name: "Tether USD", decimals: 6, contract: "0xdAC17F958D2ee523a2206206994597C13D831ec7" }
] },
{ chain: "solana", address: "9Fcm6Gw5PsivSCcpxCh9GVfj9jcPgQ8Q5mZJhsEuRHJV", tokens: [
{ symbol: "USDC", name: "USD Coin", decimals: 6, contract: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" },
{ symbol: "USDT", name: "Tether USD", decimals: 6, contract: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" }
] }
].freeze
# @param seed [Integer, String, nil] Seed value used to initialise the internal PRNG. If nil, the ENV variable DEMO_DATA_SEED will
# be honoured and default to a random seed when not present.
#
# Initialising an explicit PRNG gives us repeatable demo datasets while still
# allowing truly random data when the caller does not care about
# determinism. The global `Kernel.rand` and helpers like `Array#sample`
# will also be seeded so that *all* random behaviour inside this object –
# including library helpers that rely on Ruby's global RNG – follow the
# same deterministic sequence.
def initialize(seed: ENV.fetch("DEMO_DATA_SEED", nil))
# Convert the seed to an Integer if one was provided, otherwise fall back
# to a random, but memoised, seed so the generator instance can report it
# back to callers when needed (e.g. for debugging a specific run).
@seed = seed.present? ? seed.to_i : Random.new_seed
# Internal PRNG instance – use this instead of the global RNG wherever we
# explicitly call `rand` inside the class. We override `rand` below so
# existing method bodies automatically delegate here without requiring
# widespread refactors.
@rng = Random.new(@seed)
# Also seed Ruby's global RNG so helpers that rely on it (e.g.
# Array#sample, Kernel.rand in invoked libraries, etc.) remain
# deterministic for the lifetime of this generator instance.
srand(@seed)
end
# Expose the seed so callers can reproduce a run if necessary.
attr_reader :seed
# Generate empty family - no financial data
def generate_empty_data!(skip_clear: false)
with_timing(__method__) do
unless skip_clear
puts "🧹 Clearing existing data..."
clear_all_data!
end
puts "👥 Creating empty family..."
create_family_and_users!("Demo Family", "[email protected]", onboarded: true, subscribed: true)
puts "✅ Empty demo data loaded successfully!"
end
end
# Generate new user family - no financial data, needs onboarding
def generate_new_user_data!(skip_clear: false)
with_timing(__method__) do
unless skip_clear
puts "🧹 Clearing existing data..."
clear_all_data!
end
puts "👥 Creating new user family..."
create_family_and_users!("Demo Family", "[email protected]", onboarded: false, subscribed: false)
puts "✅ New user demo data loaded successfully!"
end
end
def generate_new_user_data_for!(family, email:)
with_timing(__method__, max_seconds: 1000) do
family = family.reload
admin_user = ensure_admin_user!(family, email)
puts "📊 Creating sample financial data for #{family.name}..."
ActiveRecord::Base.transaction do
create_realistic_categories!(family)
create_realistic_accounts!(family)
create_realistic_transactions!(family)
generate_budget_auto_fill!(family)
create_sample_rules!(family)
puts "🎯 Seeding goals..."
generate_goals!(family)
end
family.sync_later
puts "✅ Sample data loaded successfully!"
end
end
# Generate comprehensive realistic demo data with multi-currency
def generate_default_data!(skip_clear: false, email: "[email protected]")
if skip_clear
puts "⏭️ Skipping data clearing (appending new family)..."
else
puts "🧹 Clearing existing data..."
clear_all_data!
end
with_timing(__method__, max_seconds: 1000) do
puts "👥 Creating demo family..."
family = create_family_and_users!("Demo Family", email, onboarded: true, subscribed: true)
puts "📊 Creating realistic financial data..."
create_realistic_categories!(family)
create_realistic_accounts!(family)
create_realistic_transactions!(family)
# Auto-fill current-month budget based on recent spending averages
generate_budget_auto_fill!(family)
puts "📏 Creating sample rules..."
create_sample_rules!(family)
puts "🎯 Seeding goals..."
generate_goals!(family)
# Only the demo family: every family with these wallets reads the same
# addresses from the public explorers on each sync.
puts "👛 Linking public on-chain wallets..."
link_onchain_demo_wallets!(family)
puts "🔑 Creating monitoring API key..."
create_monitoring_api_key!(family)
puts "✅ Realistic demo data loaded successfully!"
end
end
private
# Simple timing helper. Pass a descriptive label and a block; the runtime
# will be printed automatically when the block completes.
# If max_seconds is provided, raise RuntimeError when the block exceeds that
# duration. Useful to keep CI/dev machines honest about demo-data perf.
def with_timing(label, max_seconds: nil)
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
result = yield
duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
puts "⏱️ #{label} completed in #{duration.round(2)}s"
if max_seconds && duration > max_seconds
raise "Demo::Generator ##{label} exceeded #{max_seconds}s (#{duration.round(2)}s)"
end
result
end
# Override Kernel#rand so *all* `rand` calls inside this instance (including
# those already present in the file) are routed through the seeded PRNG.
def rand(*args)
@rng.rand(*args)
end
def clear_all_data!
family_count = Family.count
if family_count > 50
raise "Too much data to clear efficiently (#{family_count} families). Run 'rails db:reset' instead."
end
Demo::DataCleaner.new.destroy_everything!
end
def ensure_admin_user!(family, email)
user = family.users.find_by(email: email)
return user if user&.admin? || user&.super_admin?
raise ActiveRecord::RecordNotFound, "No admin user with email #{email} found in family ##{family.id}"
end
def create_family_and_users!(family_name, email, onboarded:, subscribed:)
family = Family.create!(
name: family_name,
currency: "USD",
locale: "en",
country: "US",
timezone: "America/New_York",
date_format: "%m-%d-%Y"
)
family.start_subscription!(DEMO_STRIPE_SUBSCRIPTION_ID) if subscribed
# Admin user
family.users.create!(
email: email,
first_name: "Jack",
last_name: "Bogle",
role: "admin",
password: "Password1!",
onboarded_at: onboarded ? Time.current : nil
)
# Family member user
family.users.create!(
email: "partner_#{email}",
first_name: "Eve",
last_name: "Bogle",
role: "member",
password: "Password1!",
onboarded_at: onboarded ? Time.current : nil
)
# Demo users showcase opt-in features. Apply after creation because a new
# member's role defaults hide the AI sidebar when no provider is configured.
family.users.each do |user|
user.update!(ai_enabled: true, show_ai_sidebar: true,
preferences: user.preferences.to_h.merge("preview_features_enabled" => true))
end
family
end
def create_monitoring_api_key!(family)
admin_user = family.users.find_by(role: "admin")
return unless admin_user
# Revoke any existing user-created web API keys to keep demo access predictable.
# (the monitoring key uses the dedicated "monitoring" source and cannot be revoked)
admin_user.api_keys.active.visible.where(source: "web").find_each(&:revoke!)
existing_key = ApiKey.find_by(display_key: ApiKey::DEMO_MONITORING_KEY)
if existing_key
existing_key.update!(
user: admin_user,
name: "monitoring",
scopes: [ "read" ],
source: "monitoring",
revoked_at: nil,
expires_at: nil
)
puts " → Use existing monitoring API key"
return existing_key
end
api_key = admin_user.api_keys.create!(
name: "monitoring",
key: ApiKey::DEMO_MONITORING_KEY,
scopes: [ "read" ],
source: "monitoring"
)
puts " → Created monitoring API key: #{ApiKey::DEMO_MONITORING_KEY}"
api_key
end
def create_realistic_categories!(family)
# Income categories (3 total)
@salary_cat = family.categories.create!(name: "Salary", color: "#10b981")
@freelance_cat = family.categories.create!(name: "Freelance", color: "#059669")
@investment_income_cat = family.categories.create!(name: "Investment Income", color: "#047857")
# Expense categories with subcategories (12 total)
@housing_cat = family.categories.create!(name: "Housing", color: "#dc2626")
@rent_cat = family.categories.create!(name: "Rent/Mortgage", parent: @housing_cat, color: "#b91c1c")
@utilities_cat = family.categories.create!(name: "Utilities", parent: @housing_cat, color: "#991b1b")
@food_cat = family.categories.create!(name: "Food & Dining", color: "#ea580c")
@groceries_cat = family.categories.create!(name: "Groceries", parent: @food_cat, color: "#c2410c")
@restaurants_cat = family.categories.create!(name: "Restaurants", parent: @food_cat, color: "#9a3412")
@coffee_cat = family.categories.create!(name: "Coffee & Takeout", parent: @food_cat, color: "#7c2d12")
@transportation_cat = family.categories.create!(name: "Transportation", color: "#2563eb")
@gas_cat = family.categories.create!(name: "Gas", parent: @transportation_cat, color: "#1d4ed8")
@car_payment_cat = family.categories.create!(name: "Car Payment", parent: @transportation_cat, color: "#1e40af")
@entertainment_cat = family.categories.create!(name: "Entertainment", color: "#7c3aed")
@healthcare_cat = family.categories.create!(name: "Healthcare", color: "#db2777")
@shopping_cat = family.categories.create!(name: "Shopping", color: "#059669")
@travel_cat = family.categories.create!(name: "Travel", color: "#0891b2")
@personal_care_cat = family.categories.create!(name: "Personal Care", color: "#be185d")
# Additional high-level expense categories to reach 13 top-level items
@insurance_cat = family.categories.create!(name: "Insurance", color: "#6366f1")
@misc_cat = family.categories.create!(name: "Miscellaneous", color: "#6b7280")
# Interest expense bucket
@interest_cat = family.categories.create!(name: "Loan Interest", color: "#475569")
end
# Example rules, two groups and one rule without a group, so the rules page
# shows how rules are grouped. All are off, so the demo transactions stay as
# generated until someone switches the rules on or applies them.
def create_sample_rules!(family)
sample_rules = [
[ "Subscriptions", [ [ "Netflix", @entertainment_cat ], [ "Spotify", @entertainment_cat ] ] ],
[ "Groceries", [ [ "Whole Foods", @groceries_cat ], [ "Trader Joe's", @groceries_cat ] ] ],
[ nil, [ [ "Local Coffee", @coffee_cat ] ] ]
]
sample_rules.each do |group_name, rules|
group = family.rule_groups.find_or_create_named!(group_name) if group_name
rules.each do |name_contains, category|
family.rules.create!(
name: "#{name_contains} → #{category.name}",
resource_type: "transaction",
active: false,
rule_group: group,
conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: name_contains } ],
actions_attributes: [ { action_type: "set_transaction_category", value: category.id } ]
)
end
end
end
def create_realistic_accounts!(family)
# Checking accounts (USD)
@chase_checking = family.accounts.create!(accountable: Depository.new(subtype: "checking"), name: "Chase Premier Checking", balance: 0, currency: "USD")
@ally_checking = family.accounts.create!(accountable: Depository.new(subtype: "checking"), name: "Ally Online Checking", balance: 0, currency: "USD")
# Savings account (USD)
@marcus_savings = family.accounts.create!(accountable: Depository.new(subtype: "savings"), name: "Marcus High-Yield Savings", balance: 0, currency: "USD")
# EUR checking (EUR)
@eu_checking = family.accounts.create!(accountable: Depository.new(subtype: "checking"), name: "Deutsche Bank EUR Account", balance: 0, currency: "EUR")
# Credit cards (USD)
@amex_gold = family.accounts.create!(accountable: CreditCard.new, name: "Amex Gold Card", balance: 0, currency: "USD")
@chase_sapphire = family.accounts.create!(accountable: CreditCard.new, name: "Chase Sapphire Reserve", balance: 0, currency: "USD")
# Investment accounts (USD + GBP)
@vanguard_401k = family.accounts.create!(accountable: Investment.new, name: "Vanguard 401(k)", balance: 0, currency: "USD")
@schwab_brokerage = family.accounts.create!(accountable: Investment.new, name: "Charles Schwab Brokerage", balance: 0, currency: "USD")
@fidelity_roth_ira = family.accounts.create!(accountable: Investment.new, name: "Fidelity Roth IRA", balance: 0, currency: "USD")
@hsa_investment = family.accounts.create!(accountable: Investment.new, name: "Fidelity HSA Investment", balance: 0, currency: "USD")
@uk_isa = family.accounts.create!(accountable: Investment.new, name: "Vanguard UK ISA", balance: 0, currency: "GBP")
# Property (USD)
@home = family.accounts.create!(accountable: Property.new, name: "Primary Residence", balance: 0, currency: "USD")
# Vehicles (USD)
@honda_accord = family.accounts.create!(accountable: Vehicle.new, name: "2016 Honda Accord", balance: 0, currency: "USD")
@tesla_model3 = family.accounts.create!(accountable: Vehicle.new, name: "2021 Tesla Model 3", balance: 0, currency: "USD")
# Crypto (USD)
@coinbase_usdc = family.accounts.create!(accountable: Crypto.new, name: "Coinbase USDC", balance: 0, currency: "USD")
# Loans / Liabilities (USD). Each carries the terms its amortisation
# schedule is built from; its principal is the opening valuation written
# by open_demo_loan!. The mortgage is adjustable with two recorded rate
# changes -- a cut two years in, a rise two years later -- so the demo
# shows a schedule re-amortising. The car and student loans start the
# month before generate_loan_payments! makes their first payment.
mortgage_start = 5.years.ago.to_date
loans_start = 37.months.ago.beginning_of_month.to_date
@mortgage = family.accounts.create!(
accountable: Loan.new(
subtype: "mortgage", rate_type: "adjustable", interest_rate: 6.25, term_months: 360,
start_date: mortgage_start, initial_balance: 320_000,
# A deposit and a level-term policy, so the demo mortgage shows the
# leverage and insurance cards rather than hiding both.
down_payment: 70_000, insurance_rate: 0.36, insurance_rate_type: "level_term",
rate_changes: [
{ effective_date: (mortgage_start >> 24).iso8601, rate: "5.5" },
{ effective_date: (mortgage_start >> 48).iso8601, rate: "6.75" }
]
),
name: "Home Mortgage", balance: 0, currency: "USD"
)
@car_loan = family.accounts.create!(
accountable: Loan.new(subtype: "auto", rate_type: "fixed", interest_rate: 6.9, term_months: 60,
start_date: loans_start, initial_balance: 24_000,
# The other policy shape, on a fixed loan.
down_payment: 4_000, insurance_rate: 0.5,
insurance_rate_type: "decreasing_life"),
name: "Car Loan", balance: 0, currency: "USD"
)
@student_loan = family.accounts.create!(
accountable: Loan.new(subtype: "student", rate_type: "fixed", interest_rate: 5.5, term_months: 120,
start_date: loans_start, initial_balance: 42_000),
name: "Student Loan", balance: 0, currency: "USD"
)
@personal_loc = family.accounts.create!(accountable: OtherLiability.new, name: "Personal Line of Credit", balance: 0, currency: "USD")
@financekit_generator = Demo::FinancekitGenerator.new(family, seed: seed)
@financekit_generator.create_accounts!
# Other asset (USD)
@jewelry = family.accounts.create!(accountable: OtherAsset.new, name: "Jewelry Collection", balance: 0, currency: "USD")
end
def create_realistic_transactions!(family)
load_securities!
puts " 📈 Generating salary history (12 years)..."
generate_salary_history!
puts " 🏠 Generating housing transactions..."
generate_housing_transactions!
puts " 🍕 Generating food & dining transactions..."
generate_food_transactions!
puts " 🚗 Generating transportation transactions..."
generate_transportation_transactions!
puts " 🎬 Generating entertainment transactions..."
generate_entertainment_transactions!
puts " 🛒 Generating shopping transactions..."
generate_shopping_transactions!
puts " ⚕️ Generating healthcare transactions..."
generate_healthcare_transactions!
puts " ✈️ Generating travel transactions..."
generate_travel_transactions!
puts " 💅 Generating personal care transactions..."
generate_personal_care_transactions!
puts " 💰 Generating investment transactions..."
generate_investment_transactions!
puts " 🏡 Generating major purchases..."
generate_major_purchases!
puts " 💳 Generating transfers and payments..."
generate_transfers_and_payments!
puts " 🏦 Generating loan payments..."
generate_loan_payments!
puts " 🧾 Generating regular expense baseline..."
generate_regular_expenses!
puts " 🗄️ Generating legacy historical data..."
generate_legacy_transactions!
puts " 🔒 Generating crypto & misc asset transactions..."
generate_crypto_and_misc_assets!
puts " 👛 Generating Apple Wallet transactions..."
@financekit_generator.create_transactions!
puts " ✅ Reconciling balances to target snapshot..."
reconcile_balances!(family)
puts " 📊 Generated approximately #{Entry.joins(:account).where(accounts: { family_id: family.id }).count} transactions"
puts "🔄 Final sync to calculate adjusted balances..."
sync_family_accounts!(family)
end
# Auto-fill current-month budget based on recent spending averages
def generate_budget_auto_fill!(family)
current_month = Date.current.beginning_of_month
analysis_start = (current_month - 3.months).beginning_of_month
analysis_period = analysis_start..(current_month - 1.day)
# Fetch expense transactions in the analysis period (positive amounts = expenses)
txns = Entry.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")
.joins("INNER JOIN categories ON categories.id = transactions.category_id")
.where(entries: { entryable_type: "Transaction", date: analysis_period, account_id: family.accounts.select(:id) })
.where("entries.amount > 0")
spend_per_cat = txns.group("categories.id").sum("entries.amount")
budget = family.budgets.where(start_date: current_month).first_or_initialize
budget.update!(
end_date: current_month.end_of_month,
currency: "USD",
budgeted_spending: spend_per_cat.values.sum / 3.0, # placeholder, refine below
expected_income: 0 # Could compute similarly if desired
)
spend_per_cat.each do |cat_id, total|
avg = total / 3.0
rounded = ((avg / 25.0).round) * 25
category = Category.find(cat_id)
budget.budget_categories.find_or_create_by!(category: category) do |bc|
bc.budgeted_spending = rounded
bc.currency = "USD"
end
end
# Update aggregate budgeted_spending to sum of categories
budget.update!(budgeted_spending: budget.budget_categories.sum(:budgeted_spending))
end
# Helper method to get weighted random date (favoring recent years)
def weighted_random_date
# Focus on last 3 years for transaction generation
rand(3.years.ago.to_date..Date.current)
end
# Helper method to get random accounts for transactions
def random_checking_account
[ @chase_checking, @ally_checking ].sample
end
# ---------------------------------------------------------------------------
# Payroll system — 156 deterministic deposits (bi-weekly, six years)
# ---------------------------------------------------------------------------
def generate_salary_history!
deposit_amount = 8_500 # Increased from 4,200 to ~$200k annually
total_deposits = 78 # Reduced from 156 (only 3 years instead of 6)
# Find first Friday ≥ 3.years.ago so the cadence remains bi-weekly.
first_date = 3.years.ago.to_date
first_date += 1 until first_date.friday?
total_deposits.times do |i|
date = first_date + (14 * i)
break if date > Date.current # safety
amount = -jitter(deposit_amount, 0.02).round # negative inflow per conventions
create_transaction!(@chase_checking, amount, "Acme Corp Payroll", @salary_cat, date)
# 10 % automated savings transfer to Marcus Savings same day
savings_amount = (-amount * 0.10).round
create_transfer!(@chase_checking, @marcus_savings, savings_amount, "Auto-Save 10% of Paycheck", date)
end
# Add freelance income to help balance expenses
15.times do
date = weighted_random_date
amount = -rand(1500..4000) # Negative for income
create_transaction!(@chase_checking, amount, "Freelance Project", @freelance_cat, date)
end
# Add quarterly investment dividends
(3.years.ago.to_date..Date.current).each do |date|
next unless date.day == 15 && [ 3, 6, 9, 12 ].include?(date.month) # Quarterly
dividend_amount = -rand(800..1500) # Negative for income
create_transaction!(@chase_checking, dividend_amount, "Investment Dividends", @investment_income_cat, date)
end
# Add more regular freelance income to maintain positive checking balance
40.times do # Increased from 15
date = weighted_random_date
amount = -rand(800..2500) # More frequent, smaller freelance income
create_transaction!(@chase_checking, amount, "Freelance Payment", @freelance_cat, date)
end
# Add side income streams
25.times do
date = weighted_random_date
amount = -rand(200..800)
income_types = [ "Cash Tips", "Selling Items", "Refund", "Rebate", "Gift Card Cash Out" ]
create_transaction!(@chase_checking, amount, income_types.sample, @freelance_cat, date)
end
end
def generate_housing_transactions!
start_date = 3.years.ago.to_date # Reduced from 12 years
base_rent = 2500 # Higher starting amount for higher income family
# The mortgage is paid by generate_loan_payments!, from its own schedule.
# A flat payment booked here as well moved the loan's balance a second
# time, so the demo mortgage owed less than any schedule could explain.
# Monthly utilities (reduced frequency)
utilities = [
{ name: "ConEd Electric", range: 150..300 },
{ name: "Verizon Internet", range: 85..105 },
{ name: "Water & Sewer", range: 60..90 },
{ name: "Gas Bill", range: 80..220 }
]
utilities.each do |utility|
(start_date..Date.current).each do |date|
next unless date.day.between?(5, 15) && rand < 0.9 # Monthly with higher frequency
amount = rand(utility[:range])
create_transaction!(@chase_checking, amount, utility[:name], @utilities_cat, date)
end
end
end
def generate_food_transactions!
# Weekly groceries (increased volume but kept amounts reasonable)
120.times do # Increased from 60
date = weighted_random_date
amount = rand(60..180) # Reduced max from 220
stores = [ "Whole Foods", "Trader Joe's", "Safeway", "Stop & Shop", "Fresh Market" ]
create_transaction!(@chase_checking, amount, "#{stores.sample} Market", @groceries_cat, date)
end
# Restaurant dining (increased volume)
100.times do # Increased from 50
date = weighted_random_date
amount = rand(25..65) # Reduced max from 80
restaurants = [ "Pizza Corner", "Sushi Place", "Italian Kitchen", "Mexican Grill", "Greek Taverna" ]
create_transaction!(@chase_checking, amount, restaurants.sample, @restaurants_cat, date)
end
# Coffee & takeout (increased volume)
80.times do # Increased from 40
date = weighted_random_date
amount = rand(8..20) # Reduced from 10-25
places = [ "Local Coffee", "Dunkin'", "Corner Deli", "Food Truck" ]
create_transaction!(@chase_checking, amount, places.sample, @coffee_cat, date)
end
end
def generate_transportation_transactions!
# Gas stations (checking account only)
60.times do
date = weighted_random_date
amount = rand(35..75)
stations = [ "Shell", "Exxon", "BP", "Chevron", "Mobil", "Sunoco" ]
create_transaction!(@chase_checking, amount, "#{stations.sample} Gas", @gas_cat, date)
end
# Payments on the previous car, up to the day before the demo car loan
# starts: from then on generate_loan_payments! pays the car loan from its
# schedule, and a flat payment alongside it would count the car twice.
car_payment_start = 6.years.ago.to_date
car_payment_end = [ 1.year.ago.to_date, @car_loan.loan.start_date - 1 ].min
(car_payment_start..car_payment_end).each do |date|
next unless date.day == 15 # 15th of month
create_transaction!(@chase_checking, 385, "Auto Loan Payment", @car_payment_cat, date)
end
end
def generate_entertainment_transactions!
# Monthly subscriptions (increased timeframe)
subscriptions = [
{ name: "Netflix", amount: 15 },
{ name: "Spotify Premium", amount: 12 },
{ name: "Disney+", amount: 8 },
{ name: "HBO Max", amount: 16 },
{ name: "Amazon Prime", amount: 14 }
]
subscriptions.each do |sub|
(3.years.ago.to_date..Date.current).each do |date| # Reduced from 12 years
next unless date.day == rand(1..28) && rand < 0.9 # Higher frequency for active subscriptions
create_transaction!(@chase_checking, sub[:amount], sub[:name], @entertainment_cat, date)
end
end
# Random entertainment (increased volume)
60.times do # Increased from 25
date = weighted_random_date
amount = rand(15..60) # Reduced from 20-80
activities = [ "Movie Theater", "Sports Game", "Museum", "Comedy Club", "Bowling", "Mini Golf", "Arcade" ]
create_transaction!(@chase_checking, amount, activities.sample, @entertainment_cat, date)
end
end
def generate_shopping_transactions!
# Online shopping (increased volume)
80.times do # Increased from 40
date = weighted_random_date
amount = rand(30..90) # Reduced max from 120
stores = [ "Target.com", "Walmart", "Costco" ]
create_transaction!(@chase_checking, amount, "#{stores.sample} Purchase", @shopping_cat, date)
end
# In-store shopping (increased volume)
60.times do # Increased from 25
date = weighted_random_date
amount = rand(35..80) # Reduced max from 100
stores = [ "Target", "REI", "Barnes & Noble", "GameStop" ]
create_transaction!(@chase_checking, amount, stores.sample, @shopping_cat, date)
end
end
def generate_healthcare_transactions!
# Doctor visits (increased volume)
45.times do # Increased from 25
date = weighted_random_date
amount = rand(150..350) # Reduced from 180-450
providers = [ "Dr. Smith", "Dr. Johnson", "Dr. Williams", "Specialist Visit", "Urgent Care" ]
create_transaction!(@chase_checking, amount, providers.sample, @healthcare_cat, date)
end
# Pharmacy (increased volume)
80.times do # Increased from 40
date = weighted_random_date
amount = rand(12..65) # Reduced from 15-85
pharmacies = [ "CVS Pharmacy", "Walgreens", "Rite Aid", "Local Pharmacy" ]
create_transaction!(@chase_checking, amount, pharmacies.sample, @healthcare_cat, date)
end
end
def generate_travel_transactions!
# Major vacations (reduced count - premium travel handled in credit card cycles)
8.times do
date = weighted_random_date
# Smaller local trips from checking
hotel_amount = rand(200..500)
hotels = [ "Local Hotel", "B&B", "Nearby Resort" ]
if rand < 0.3 && date > 3.years.ago.to_date # Some EUR transactions
create_transaction!(@eu_checking, hotel_amount, hotels.sample, @travel_cat, date)
else
create_transaction!(@chase_checking, hotel_amount, hotels.sample, @travel_cat, date)
end
# Domestic flights (smaller amounts)
flight_amount = rand(200..400)
create_transaction!(@chase_checking, flight_amount, "Domestic Flight", @travel_cat, date + rand(1..5).days)
# Local activities
activity_amount = rand(50..150)
activities = [ "Local Tour", "Museum Tickets", "Activity Pass" ]
create_transaction!(@chase_checking, activity_amount, activities.sample, @travel_cat, date + rand(1..7).days)
end
end
def generate_personal_care_transactions!
# Gym membership
(12.years.ago.to_date..Date.current).each do |date|
next unless date.day == 1 && rand < 0.8 # Monthly
create_transaction!(@chase_checking, 45, "Gym Membership", @personal_care_cat, date)
end
# Beauty/grooming (checking account only)
40.times do
date = weighted_random_date
amount = rand(25..80)
services = [ "Hair Salon", "Barber Shop", "Nail Salon" ]
create_transaction!(@chase_checking, amount, services.sample, @personal_care_cat, date)
end
end
def generate_investment_transactions!
security = Security.first || Security.create!(ticker: "VTI", name: "Vanguard Total Stock Market ETF", country_code: "US")
generate_401k_trades!(security)
generate_brokerage_trades!(security)
generate_roth_trades!(security)
generate_uk_isa_trades!(security)
end
# ---------------------------------------------------- 401k (180 trades) --
def generate_401k_trades!(security)
payroll_dates = collect_payroll_dates.first(90) # 90 paydays ⇒ 180 trades
payroll_dates.each do |date|
# Employee contribution $1 200
create_trade_for(@vanguard_401k, security, 1_200, date, "401k Employee")
# Employer match $300
create_trade_for(@vanguard_401k, security, 300, date, "401k Employer Match")
end
end
# -------------------------------------------- Brokerage (144 trades) -----
def generate_brokerage_trades!(security)
date_cursor = 36.months.ago.beginning_of_month
while date_cursor <= Date.current
4.times do |i|
trade_date = date_cursor + i * 7.days # roughly spread within month
create_trade_for(@schwab_brokerage, security, rand(400..1_000), trade_date, "Brokerage Purchase")
end
date_cursor = date_cursor.next_month.beginning_of_month
end
end
# ----------------------------------------------- Roth IRA (108 trades) ---
def generate_roth_trades!(security)
date_cursor = 36.months.ago.beginning_of_month
while date_cursor <= Date.current
# Split $500 monthly across 3 staggered trades
3.times do |i|
trade_date = date_cursor + i * 10.days
create_trade_for(@fidelity_roth_ira, security, (500 / 3.0), trade_date, "Roth IRA Contribution")
end
date_cursor = date_cursor.next_month.beginning_of_month
end
end
# ------------------------------------------------- UK ISA (108 trades) ----
def generate_uk_isa_trades!(security)
date_cursor = 36.months.ago.beginning_of_month
while date_cursor <= Date.current
3.times do |i|
trade_date = date_cursor + i * 10.days
create_trade_for(@uk_isa, security, (400 / 3.0), trade_date, "ISA Investment", price_range: 60..150)
end
date_cursor = date_cursor.next_month.beginning_of_month
end
end
# --------------------------- Helpers for investment trade generation -----
def collect_payroll_dates
dates = []
d = 36.months.ago.to_date
d += 1 until d.friday?
while d <= Date.current
dates << d if d.cweek.even?
d += 14 # next bi-weekly
end
dates
end
def create_trade_for(account, security, investment_amount, date, memo, price_range: 80..200)
price = rand(price_range)
qty = (investment_amount.to_f / price).round(2)
create_investment_transaction!(account, security, qty, price, date, memo)
end
def generate_major_purchases!
# Home purchase (5 years ago) - only record the down payment, not full value
# Property value will be set by valuation in reconcile_balances!
home_date = @mortgage.loan.start_date
create_transaction!(@chase_checking, 70_000, "Home Down Payment", @housing_cat, home_date)
# Each loan opens at its principal on its start date -- the mortgage's
# 320,000 among them. A valuation rather than a transaction, because
# Loan#original_balance reads the first valuation: recorded as a
# transaction, the debt left the schedule with no principal to amortise.
[ @mortgage, @car_loan, @student_loan ].each { |loan_account| open_demo_loan!(loan_account) }
# Initial account funding (realistic amounts)
create_transaction!(@chase_checking, -5_000, "Initial Deposit", @salary_cat, 12.years.ago.to_date)
create_transaction!(@ally_checking, -2_000, "Initial Deposit", @salary_cat, 12.years.ago.to_date)
create_transaction!(@marcus_savings, -10_000, "Initial Savings", @salary_cat, 12.years.ago.to_date)
create_transaction!(@eu_checking, -5_000, "EUR Account Opening", nil, 4.years.ago.to_date)
# Car purchases (realistic amounts)
create_transaction!(@chase_checking, 3_000, "Car Down Payment", @transportation_cat, 6.years.ago.to_date)
create_transaction!(@chase_checking, 2_500, "Second Car Down Payment", @transportation_cat, 8.years.ago.to_date)
# Major but realistic expenses
create_transaction!(@chase_checking, 8_000, "Kitchen Renovation", @utilities_cat, 2.years.ago.to_date)
create_transaction!(@chase_checking, 5_000, "Bathroom Remodel", @utilities_cat, 1.year.ago.to_date)
create_transaction!(@chase_checking, 12_000, "Roof Replacement", @utilities_cat, 3.years.ago.to_date)
create_transaction!(@chase_checking, 8_000, "Family Emergency", @healthcare_cat, 4.years.ago.to_date)
create_transaction!(@chase_checking, 15_000, "Wedding Expenses", @entertainment_cat, 9.years.ago.to_date)
end
# The opening anchor valuation a loan account created through the form
# would carry: the loan's principal on its start date.
def open_demo_loan!(account)
loan = account.loan
account.entries.create!(
entryable: Valuation.new(kind: "opening_anchor"),
amount: loan.initial_balance,
name: Valuation.build_opening_anchor_name(account.accountable_type),
currency: account.currency,
date: loan.start_date
)
end
def generate_transfers_and_payments!
generate_credit_card_cycles!
generate_monthly_ally_transfers!
generate_quarterly_fx_transfers!
generate_additional_savings_transfers!
end
# Additional savings transfers to improve income/expense balance
def generate_additional_savings_transfers!
# Monthly extra savings transfers
(3.years.ago.to_date..Date.current).each do |date|
next unless date.day == 15 && rand < 0.7 # Semi-monthly savings
amount = rand(500..1500)
create_transfer!(@chase_checking, @marcus_savings, amount, "Extra Savings Transfer", date)
end
# Quarterly HSA contributions
(3.years.ago.to_date..Date.current).each do |date|
next unless date.day == 1 && [ 1, 4, 7, 10 ].include?(date.month) # Quarterly
amount = rand(1000..2000)
create_transfer!(@chase_checking, @hsa_investment, amount, "HSA Contribution", date)
end
# Occasional windfalls (tax refunds, bonuses, etc.)
8.times do
date = weighted_random_date
amount = rand(2000..8000)
create_transaction!(@chase_checking, -amount, "Tax Refund/Bonus", @salary_cat, date)
end
# CRITICAL: Regular transfers FROM savings TO checking to maintain positive balance
# This is realistic - people move money from savings to checking regularly
(3.years.ago.to_date..Date.current).each do |date|
next unless date.day == rand(20..28) && rand < 0.8 # Monthly transfers from savings
amount = rand(2000..5000)
create_transfer!(@marcus_savings, @chase_checking, amount, "Transfer from Savings", date)
end
# Weekly smaller transfers from savings for cash flow
(3.years.ago.to_date..Date.current).each do |date|
next unless date.wday == 1 && rand < 0.4 # Some Mondays
amount = rand(500..1200)
create_transfer!(@marcus_savings, @chase_checking, amount, "Weekly Cash Flow", date)
end
end
# $300 from Chase Checking to Ally Checking on the first business day of each
# month for the past 36 months.
def generate_monthly_ally_transfers!
date_cursor = 36.months.ago.beginning_of_month
while date_cursor <= Date.current
transfer_date = first_business_day(date_cursor)
create_transfer!(@chase_checking, @ally_checking, 300, "Monthly Ally Transfer", transfer_date)
date_cursor = date_cursor.next_month.beginning_of_month
end
end
# Quarterly $2 000 FX transfer from Chase Checking to EUR account
def generate_quarterly_fx_transfers!
date_cursor = 36.months.ago.beginning_of_quarter
while date_cursor <= Date.current
transfer_date = date_cursor + 2.days # arbitrary within quarter start
create_transfer!(@chase_checking, @eu_checking, 2_000, "Quarterly FX Transfer", transfer_date)
date_cursor = date_cursor.next_quarter.beginning_of_quarter
end
end
# Returns the first weekday (Mon-Fri) of the month containing +date+.
def first_business_day(date)
d = date.beginning_of_month
d += 1.day while d.saturday? || d.sunday?
d
end
def generate_credit_card_cycles!
# REDUCED: 30-45 charges per month across both cards for 36 months (≈1,400 total)
# This is still significant but more realistic than 80-120/month
# Pay 90-95 % of new balance 5 days post-cycle; final balances should
# be ~$2 500 (Amex) and ~$4 200 (Sapphire).
start_date = 36.months.ago.beginning_of_month
end_date = Date.current.end_of_month
amex_balance = 0
sapphire_balance = 0
charges_this_run = 0
payments_this_run = 0
date_cursor = start_date
while date_cursor <= end_date
# --- Charge generation (REDUCED FOR BALANCE) -------------------------
month_charge_target = rand(30..45) # Reduced from 80-120 to 30-45
# Split roughly evenly but add a little variance.
amex_count = (month_charge_target * rand(0.45..0.55)).to_i
sapphire_count = month_charge_target - amex_count
amex_total = generate_credit_card_charges(@amex_gold, date_cursor, amex_count)
sapphire_total = generate_credit_card_charges(@chase_sapphire, date_cursor, sapphire_count)
amex_balance += amex_total
sapphire_balance += sapphire_total
charges_this_run += (amex_count + sapphire_count)
# --- Monthly payments (5 days after month end) ------------------------
payment_date = (date_cursor.end_of_month + 5.days)
if amex_total.positive?
amex_payment = (amex_total * rand(0.90..0.95)).round
create_transfer!(@chase_checking, @amex_gold, amex_payment, "Amex Payment", payment_date)
amex_balance -= amex_payment
payments_this_run += 1
end
if sapphire_total.positive?
sapphire_payment = (sapphire_total * rand(0.90..0.95)).round
create_transfer!(@chase_checking, @chase_sapphire, sapphire_payment, "Sapphire Payment", payment_date)
sapphire_balance -= sapphire_payment
payments_this_run += 1
end
date_cursor = date_cursor.next_month.beginning_of_month
end
# -----------------------------------------------------------------------
# Re-balance to hit target ending balances (tolerance ±$250)
# -----------------------------------------------------------------------
target_amex = 2_500
target_sapphire = 4_200
diff_amex = amex_balance - target_amex
diff_sapphire = sapphire_balance - target_sapphire
if diff_amex > 250
create_transfer!(@chase_checking, @amex_gold, diff_amex, "Amex Balance Adjust", Date.current)
amex_balance -= diff_amex
elsif diff_amex < -250
# Balance landed below target: a transfer can't have a negative payment
# amount, so bring the card up to target with a direct charge instead.
shortfall = diff_amex.abs
create_transaction!(@amex_gold, shortfall, "Balance Reconciliation", random_expense_category, Date.current)
amex_balance += shortfall
end
if diff_sapphire > 250
create_transfer!(@chase_checking, @chase_sapphire, diff_sapphire, "Sapphire Balance Adjust", Date.current)
sapphire_balance -= diff_sapphire
elsif diff_sapphire < -250
shortfall = diff_sapphire.abs
create_transaction!(@chase_sapphire, shortfall, "Balance Reconciliation", random_expense_category, Date.current)
sapphire_balance += shortfall
end
puts " 💳 Charges generated: #{charges_this_run} | Payments: #{payments_this_run}"
puts " 💳 Final Amex balance: ~$#{amex_balance} | target ~$#{target_amex}"
puts " 💳 Final Sapphire balance: ~$#{sapphire_balance} | target ~$#{target_sapphire}"
end
# Generate exactly +count+ charges on +account+ within the month of +base_date+.
# Returns total charge amount.
def generate_credit_card_charges(account, base_date, count)
total = 0
count.times do
charge_date = base_date + rand(0..27).days
amount = rand(15..80) # Reduced from 25..150 due to higher frequency
# bias amounts to achieve reasonable monthly totals
amount = jitter(amount, 0.15).round
merchant = if account == @amex_gold
pick(%w[WholeFoods Starbucks UberEats Netflix LocalBistro AirBnB])
else
pick([ "Delta Airlines", "Hilton Hotels", "Expedia", "Apple", "BestBuy", "Amazon" ])
end
create_transaction!(account, amount, merchant, random_expense_category, charge_date)
total += amount
end
total
end
def random_expense_category
[ @food_cat, @entertainment_cat, @shopping_cat, @travel_cat, @transportation_cat ].sample
end
def create_transaction!(account, amount, name, category, date)
# For credit cards (liabilities), positive amounts = charges (increase debt)
# For checking accounts (assets), positive amounts = expenses (decrease balance)
# The amount is already signed correctly by the caller
account.entries.create!(
entryable: Transaction.new(category: category),
amount: amount,
name: name,
currency: account.currency,
date: date
)
end
def create_investment_transaction!(account, security, qty, price, date, name)
account.entries.create!(
entryable: Trade.new(security: security, qty: qty, price: price, currency: account.currency),
amount: -(qty * price),
name: name,
currency: account.currency,
date: date
)
end
def create_transfer!(from_account, to_account, amount, name, date)
outflow = from_account.entries.create!(
entryable: Transaction.new,
amount: amount,
name: name,
currency: from_account.currency,
date: date
)
inflow = to_account.entries.create!(
entryable: Transaction.new,
amount: -amount,
name: name,
currency: to_account.currency,
date: date
)
# Confirmed, as Transfer::Creator makes a transfer the user records: a
# pending one is an auto-match suggestion, which reports leave unlinked.
Transfer.create!(inflow_transaction: inflow.entryable, outflow_transaction: outflow.entryable, status: "confirmed")
end
def load_securities!
return if Security.exists?
Security.create!([
{ ticker: "VTI", name: "Vanguard Total Stock Market ETF", country_code: "US" },
{ ticker: "VXUS", name: "Vanguard Total International Stock ETF", country_code: "US" },
{ ticker: "BND", name: "Vanguard Total Bond Market ETF", country_code: "US" }
])
end
def sync_family_accounts!(family)
family.accounts.each do |account|
sync = Sync.create!(syncable: account)
sync.perform
end
end
# Linked the way a user links them, from an empty snapshot instead of a chain
# read, so generating stays offline. The item sync the linker queues fills in
# the real balances, history and prices.
#
# One transaction: jobs are enqueued after commit, so the sync the first link
# queues starts with every wallet linked rather than with the first alone.
def link_onchain_demo_wallets!(family)
item = family.onchain_wallet_item!
item.transaction do
ONCHAIN_DEMO_WALLETS.each do |wallet|
chain = Onchain::Chains.find!(wallet[:chain])
assets = [ chain.native_asset(quantity: 0) ] + wallet[:tokens].map { |token| chain.token_asset(**token, quantity: 0) }
OnchainWalletItem::WalletLinker.new(item, chain: chain.key, address: Onchain::Chains.canonical_address(chain.key, wallet[:address]))
.link(snapshot: Onchain::Snapshot.new(assets: assets, movements: []), selected_keys: assets.map { |asset| OnchainWalletItem::TokenReview.key_for(asset) })
end
end
end
# ---------------------------------------------------------------------------
# Deterministic helper methods
# ---------------------------------------------------------------------------
# Deterministically walk through the elements of +array+, returning the next
# element each time it is called with the *same* array instance.
#
# Example:
# colours = %w[red green blue]
# 4.times.map { pick(colours) } #=> ["red", "green", "blue", "red"]
def pick(array)
@pick_indices ||= Hash.new(0)
idx = @pick_indices[array.object_id]
@pick_indices[array.object_id] += 1
array[idx % array.length]
end
# Adds a small random variation (±pct, default 3%) to +num+. Useful for
# making otherwise deterministic amounts look more natural while retaining
# overall reproducibility via the seeded RNG.
def jitter(num, pct = 0.03)
variation = num * pct * (rand * 2 - 1) # rand(-pct..pct)
(num + variation).round(2)
end
# ---------------------------------------------------------------------------
# Loan payments (Task 8)
# ---------------------------------------------------------------------------
# The one extra principal payment the student loan makes, a year ago.
STUDENT_LOAN_EXTRA_PAYMENT = 2_000
# Each demo loan pays what its own schedule asks, split into that payment's
# principal and interest, on every scheduled date up to today, so its
# balance is the one its schedule gives. Flat figures here (600 principal
# and 1,100 interest on the mortgage, whatever its rate) left the balances
# disagreeing with the schedules beside them. The student loan also makes
# one extra payment, so the demo shows a loan ahead of schedule for a real
# reason; the mortgage and the car loan sit on theirs.
def generate_loan_payments!
[
[ @mortgage, "Mortgage Payment", @rent_cat ],
[ @student_loan, "Student Loan Payment", @interest_cat ],
[ @car_loan, "Auto Loan Payment", @transportation_cat ]
].each do |account, memo, interest_category|
# Loan's touch callback can cache a missing account while it is saved
# before its parent. Within a sample-data/refresh transaction, the
# after-commit cache reset has not run yet, so reload before scheduling.
account.loan.reload.amortization_schedule.payments.each do |payment|
break if payment.date > Date.current
make_loan_payment!(
principal_account: account,
principal_amount: payment.principal.amount,
interest_amount: payment.interest.amount,
interest_category: interest_category,
date: payment.date,
memo: memo
)
end
end
create_transfer!(@chase_checking, @student_loan, STUDENT_LOAN_EXTRA_PAYMENT, "Student Loan Extra Payment", 1.year.ago.to_date)
end
def make_loan_payment!(principal_account:, principal_amount:, interest_amount:, interest_category:, date:, memo:)
# Principal portion – transfer from checking to loan account
create_transfer!(@chase_checking, principal_account, principal_amount, memo, date)
# Interest portion – expense from checking
create_transaction!(@chase_checking, interest_amount, "#{memo} Interest", interest_category, date)
end
# Generate additional baseline expenses to reach 8k-12k transaction target
def generate_regular_expenses!
expense_generators = [
->(date) { create_transaction!(@chase_checking, jitter(rand(150..220), 0.05).round, pick([ "ConEd Electric", "National Grid", "Gas & Power" ]), @utilities_cat, date) },
->(date) { create_transaction!(@chase_checking, jitter(rand(10..20), 0.1).round, pick([ "Spotify", "Netflix", "Hulu", "Apple One" ]), @entertainment_cat, date) },
->(date) { create_transaction!(@chase_checking, jitter(rand(45..90), 0.1).round, pick([ "Whole Foods", "Trader Joe's", "Safeway" ])+" Market", @groceries_cat, date) },
->(date) { create_transaction!(@chase_checking, jitter(rand(25..50), 0.1).round, pick([ "Shell Gas", "BP Gas", "Exxon" ]), @gas_cat, date) },
->(date) { create_transaction!(@chase_checking, jitter(rand(15..40), 0.1).round, pick([ "Movie Streaming", "Book Purchase", "Mobile Game" ]), @entertainment_cat, date) }
]
desired = 600 # Increased from 300 to help reach 8k
current = Entry.joins(:account).where(accounts: { id: [ @chase_checking.id ] }, entryable_type: "Transaction").count
to_create = [ desired - current, 0 ].max
to_create.times do
date = weighted_random_date
expense_generators.sample.call(date)
end
# Add high-volume, low-impact transactions to reach 8k minimum
generate_micro_transactions!
end
# Generate many small transactions to reach volume target
def generate_micro_transactions!
# ATM withdrawals and fees (reduced)
120.times do # Reduced from 200
date = weighted_random_date
amount = rand(20..60)
create_transaction!(@chase_checking, amount, "ATM Withdrawal", @misc_cat, date)
# Small ATM fee
create_transaction!(@chase_checking, rand(2..4), "ATM Fee", @misc_cat, date)
end
# Small convenience store purchases (reduced)
200.times do # Reduced from 300
date = weighted_random_date
amount = rand(3..15)
stores = [ "7-Eleven", "Wawa", "Circle K", "Quick Stop", "Corner Store" ]
create_transaction!(@chase_checking, amount, stores.sample, @shopping_cat, date)
end
# Small digital purchases (reduced)
120.times do # Reduced from 200
date = weighted_random_date
amount = rand(1..10)
items = [ "App Store", "Google Play", "iTunes", "Steam", "Kindle Book" ]
create_transaction!(@chase_checking, amount, items.sample, @entertainment_cat, date)
end
# Parking meters and tolls (reduced)
100.times do # Reduced from 150
date = weighted_random_date
amount = rand(2..8)
create_transaction!(@chase_checking, amount, pick([ "Parking Meter", "Bridge Toll", "Tunnel Toll" ]), @transportation_cat, date)
end
# Small cash transactions (reduced)
150.times do # Reduced from 250
date = weighted_random_date
amount = rand(5..25)
vendors = [ "Food Truck", "Farmer's Market", "Street Vendor", "Tip", "Donation" ]
create_transaction!(@chase_checking, amount, vendors.sample, @misc_cat, date)
end
# Vending machine purchases (reduced)
60.times do # Reduced from 100
date = weighted_random_date
amount = rand(1..5)
create_transaction!(@chase_checking, amount, "Vending Machine", @shopping_cat, date)
end
# Public transportation (reduced)
120.times do # Reduced from 180
date = weighted_random_date
amount = rand(2..8)
transit = [ "Metro Card", "Bus Fare", "Train Ticket", "Uber/Lyft" ]
create_transaction!(@chase_checking, amount, transit.sample, @transportation_cat, date)
end
# Additional small transactions to ensure we reach 8k minimum (reduced)
400.times do # Reduced from 600
date = weighted_random_date
amount = rand(1..12)
merchants = [
"Newsstand", "Coffee Cart", "Tip Jar", "Donation Box", "Laundromat",
"Car Wash", "Redbox", "PayPhone", "Photo Booth", "Arcade Game",
"Postage", "Newspaper", "Lottery Ticket", "Gumball Machine", "Ice Cream Truck"
]
create_transaction!(@chase_checking, amount, merchants.sample, @misc_cat, date)
end
# Extra small transactions to ensure 8k+ volume
500.times do
date = weighted_random_date
amount = rand(1..8)
tiny_merchants = [
"Candy Machine", "Sticker Machine", "Penny Scale", "Charity Donation",
"Busker Tip", "Church Offering", "Lemonade Stand", "Girl Scout Cookies",
"Raffle Ticket", "Bake Sale", "Car Wash Tip", "Street Performer"
]
create_transaction!(@chase_checking, amount, tiny_merchants.sample, @misc_cat, date)
end
end
# ---------------------------------------------------------------------------
# Legacy historical transactions (Task 11)
# ---------------------------------------------------------------------------
def generate_legacy_transactions!
# Small recent legacy transactions (3-6 years ago)
count = rand(40..60) # Increased from 20-30
count.times do
years_ago = rand(3..6)
date = years_ago.years.ago.to_date - rand(0..364).days
base_amount = rand(12..45) # Reduced from 15-60
discount = (1 - 0.02 * [ years_ago - 3, 0 ].max)
amount = (base_amount * discount).round
account = [ @chase_checking, @ally_checking ].sample
category = pick([ @groceries_cat, @utilities_cat, @gas_cat, @restaurants_cat, @shopping_cat ])
merchant = case category
when @groceries_cat then pick(%w[Walmart Kroger Safeway]) + " Market"
when @utilities_cat then pick([ "Local Electric", "City Water", "Gas Co." ])
when @gas_cat then pick(%w[Shell Exxon BP])
when @restaurants_cat then pick([ "Diner", "Burger Grill", "Pizza Place" ])
else pick([ "General Store", "Department Shop", "Outlet" ])
end
create_transaction!(account, amount, merchant, category, date)
end
# Very old transactions (7-15 years ago) - just scattered outliers
count = rand(25..40) # Increased from 15-25
count.times do
years_ago = rand(7..15)
date = years_ago.years.ago.to_date - rand(0..364).days
base_amount = rand(8..30) # Reduced from 10-40
discount = (1 - 0.03 * [ years_ago - 7, 0 ].max) # More discount for very old
amount = (base_amount * discount).round.clamp(5, 25) # Reduced max from 35
account = @chase_checking # Just use main checking for simplicity
category = pick([ @groceries_cat, @gas_cat, @restaurants_cat ])
merchant = case category
when @groceries_cat then pick(%w[Walmart Kroger]) + " Market"
when @gas_cat then pick(%w[Shell Exxon])
else pick([ "Old Diner", "Local Restaurant" ])
end
create_transaction!(account, amount, "#{merchant} (#{years_ago}y ago)", category, date)
end
# Additional small transactions to reach 8k minimum if needed
additional_needed = [ 400, 0 ].max # Increased from 200
additional_needed.times do
years_ago = rand(4..12)
date = years_ago.years.ago.to_date - rand(0..364).days
amount = rand(6..20) # Reduced from 8-25
account = [ @chase_checking, @ally_checking ].sample
category = pick([ @groceries_cat, @gas_cat, @utilities_cat ])
merchant = "Legacy #{pick(%w[Store Gas Electric])}"
create_transaction!(account, amount, merchant, category, date)
end
end
# ---------------------------------------------------------------------------
# Crypto & misc assets (Task 12)
# ---------------------------------------------------------------------------
def generate_crypto_and_misc_assets!
# One-time USDC deposit 18 months ago
deposit_date = 18.months.ago.to_date
create_transaction!(@coinbase_usdc, -3_500, "Initial USDC Deposit", nil, deposit_date)
end
# ---------------------------------------------------------------------------
# Balance Reconciliation (Task 14)
# ---------------------------------------------------------------------------
def reconcile_balances!(family)
# Use valuations only for property/vehicle accounts that should have specific values
# All other accounts should reach target balances through natural transaction flow
# Property valuations (these accounts are valued, not transaction-driven)
@home.entries.create!(
entryable: Valuation.new(kind: "current_anchor"),
amount: 350_000,
name: Valuation.build_current_anchor_name(@home.accountable_type),
currency: "USD",
date: Date.current
)
# Vehicle valuations (these depreciate over time)
@honda_accord.entries.create!(
entryable: Valuation.new(kind: "current_anchor"),
amount: 18_000,
name: Valuation.build_current_anchor_name(@honda_accord.accountable_type),
currency: "USD",
date: Date.current
)
@tesla_model3.entries.create!(
entryable: Valuation.new(kind: "current_anchor"),
amount: 4_500,
name: Valuation.build_current_anchor_name(@tesla_model3.accountable_type),
currency: "USD",
date: Date.current
)
@jewelry.entries.create!(
entryable: Valuation.new(kind: "reconciliation"),
amount: 2000,
name: Valuation.build_reconciliation_name(@jewelry.accountable_type),
currency: "USD",
date: 90.days.ago.to_date
)
@personal_loc.entries.create!(
entryable: Valuation.new(kind: "reconciliation"),
amount: 800,
name: Valuation.build_reconciliation_name(@personal_loc.accountable_type),
currency: "USD",
date: 120.days.ago.to_date
)
puts " ✅ Set property and vehicle valuations"
end
def generate_goals!(family)
# Order so primary/secondary picks stay stable across reseeds — the
# state-coverage matrix below routes goals to specific accounts to
# surface every status branch, so DB return order can't pick.
depository_accounts = family.accounts
.where(accountable_type: "Depository")
.visible
.order(:created_at, :id)
.to_a
return if depository_accounts.empty?
currency = depository_accounts.first.currency
eligible = depository_accounts.select { |a| a.currency == currency }
primary = eligible.first
secondary = (eligible - [ primary ]).first || primary
# Demo coverage matrix. The demo seeds a heavy primary checking
# balance (~$150k) plus a smaller secondary account (~$10k). To
# surface every goal state we deliberately route goals to different
# account pools so progress lands above or below the target:
#
# AASM states: active, paused, completed, archived
# Computed status (on active goals):
# :reached, :on_track, :behind, :no_target_date
# Edge surfaces: past-due target_date ("was due"), open pledge
# banner, matched pledge ("last pledge matched")
goals = [
# active · behind — secondary account only, target above its balance
{
name: "Vacation in Italy",
target: 20_000,
target_date: 4.months.from_now.to_date,
accounts: [ secondary ],
allocations: { secondary => 3_000 },
pledges: [
{ account: secondary, amount: 250, kind: "transfer", status: "open", expires_at: 5.days.from_now }
]
},
# active · reached — earmark comfortably above target
{
name: "Wedding fund",
target: 2_400,
target_date: 12.months.from_now.to_date,
accounts: [ primary ],
allocations: { primary => 2_500 }
},
# active · no_target_date — secondary so progress doesn't auto-cap at 100%
{
name: "Emergency fund",
target: 30_000,
target_date: nil,
accounts: [ secondary ],
allocations: { secondary => 3_000 }
},
# active · behind big — combined pools still well short of the target
{
name: "House downpayment",
target: 500_000,
target_date: 24.months.from_now.to_date,
accounts: eligible.first(2),
allocations: { primary => 1_000, secondary => 2_000 },
pledges: [
{ account: primary, amount: 2_000, kind: "transfer", status: "open", expires_at: 4.days.from_now }
]
},
# active · on_track — the one goal left holding all of `primary`, so
# its balance stays close enough to the target for a 60-month pace to
# read as on track
{
name: "Long-term portfolio",
target: 200_000,
target_date: 60.months.from_now.to_date,
accounts: [ primary ]
},
# active · past-due — exercises "was due" header copy + the
# months_remaining = 0 branch in monthly_target_amount
{
name: "Tax prep buffer",
target: 1_200,
target_date: 2.months.ago.to_date,
accounts: [ secondary ],
allocations: { secondary => 1_000 }
},
# AASM paused
{
name: "Sabbatical",
target: 15_000,
target_date: 18.months.from_now.to_date,
state: "paused",
accounts: [ primary ],
allocations: { primary => 1_000 }
},
# AASM archived
{
name: "Old laptop fund",
target: 1_500,
target_date: 12.months.ago.to_date,
state: "archived",
accounts: [ primary ],
allocations: { primary => 500 }
},
# AASM completed
{
name: "Paid-off car",
target: 8_000,
target_date: 6.months.ago.to_date,
state: "completed",
accounts: [ primary ],
allocations: { primary => 8_000 }
}
]
wedding_goal = nil
goals.each do |goal_spec|
goal = family.goals.new(
name: goal_spec[:name],
target_amount: goal_spec[:target],
target_date: goal_spec[:target_date],
currency: currency,
color: Goal::COLORS.sample,
state: goal_spec[:state] || "active"
)
goal_spec[:accounts].uniq.each do |a|
goal.goal_accounts.build(account: a, allocated_amount: goal_spec.dig(:allocations, a))
end
goal.save!
wedding_goal = goal if goal_spec[:name] == "Wedding fund"
Array(goal_spec[:pledges]).each do |pledge_spec|
goal.goal_pledges.create!(
account: pledge_spec[:account] || goal.linked_accounts.first,
amount: pledge_spec[:amount],
currency: currency,
kind: pledge_spec[:kind] || "transfer",
status: pledge_spec[:status] || "open",
expires_at: pledge_spec[:expires_at] || 7.days.from_now
)
end
end
seed_matched_pledge_demo_for_wedding!(wedding_goal, currency, primary) if wedding_goal && primary
puts " ✅ Seeded #{goals.size} goals"
end
# Bind one matched pledge on the Wedding fund to a real recent demo
# inflow Transaction. Surfaces the "Last pledge matched N days ago"
# header copy + exercises the partial-unique index on
# transactions.extra->'goal'->>'pledge_id'.
def seed_matched_pledge_demo_for_wedding!(wedding, currency, primary)
return unless wedding && primary
recent_inflow_entry = Entry
.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")
.where(account_id: primary.id, excluded: false)
.where("entries.amount < 0")
.where("entries.date >= ?", 30.days.ago.to_date)
.where("(transactions.extra -> 'goal' ->> 'pledge_id') IS NULL")
.order("entries.date DESC", "entries.id DESC")
.first
return unless recent_inflow_entry
pledge = wedding.goal_pledges.create!(
account: primary,
amount: recent_inflow_entry.amount.to_d.abs,
currency: currency,
kind: "transfer",
status: "matched",
matched_transaction_id: recent_inflow_entry.entryable_id,
expires_at: 7.days.ago
)
txn = recent_inflow_entry.entryable
new_extra = (txn.extra || {}).deep_dup
new_extra["goal"] = (new_extra["goal"] || {}).merge("pledge_id" => pledge.id)
txn.update!(extra: new_extra)
end
end