mirror of
https://github.com/maybe-finance/maybe.git
synced 2025-07-18 20:59:39 +02:00
* add kind to transaction model * Basic transfer creator * Fix method naming conflict * Creator form pattern * Remove stale methods * Tweak migration * Remove BaseQuery, write entire query in each class for clarity * Query optimizations * Remove unused exchange rate query lines * Remove temporary cache-warming strategy * Fix test * Update transaction search * Decouple transactions endpoint from IncomeStatement * Clean up transactions controller * Update cursor rules * Cleanup comments, logic in search * Fix totals logic on transactions view * Fix pagination * Optimize search totals query * Default to last 30 days on transactions page if no filters * Decouple transactions list from transfer details * Revert transfer route * Migration reset * Bundle update * Fix matching logic, tests * Remove unused code
58 lines
1.7 KiB
Ruby
58 lines
1.7 KiB
Ruby
class IncomeStatement::FamilyStats
|
|
def initialize(family, interval: "month")
|
|
@family = family
|
|
@interval = interval
|
|
end
|
|
|
|
def call
|
|
ActiveRecord::Base.connection.select_all(sanitized_query_sql).map do |row|
|
|
StatRow.new(
|
|
classification: row["classification"],
|
|
median: row["median"],
|
|
avg: row["avg"]
|
|
)
|
|
end
|
|
end
|
|
|
|
private
|
|
StatRow = Data.define(:classification, :median, :avg)
|
|
|
|
def sanitized_query_sql
|
|
ActiveRecord::Base.sanitize_sql_array([
|
|
query_sql,
|
|
{
|
|
target_currency: @family.currency,
|
|
interval: @interval,
|
|
family_id: @family.id
|
|
}
|
|
])
|
|
end
|
|
|
|
def query_sql
|
|
<<~SQL
|
|
WITH period_totals AS (
|
|
SELECT
|
|
date_trunc(:interval, ae.date) as period,
|
|
CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,
|
|
SUM(ae.amount * COALESCE(er.rate, 1)) as total
|
|
FROM transactions t
|
|
JOIN entries ae ON ae.entryable_id = t.id AND ae.entryable_type = 'Transaction'
|
|
JOIN accounts a ON a.id = ae.account_id
|
|
LEFT JOIN exchange_rates er ON (
|
|
er.date = ae.date AND
|
|
er.from_currency = ae.currency AND
|
|
er.to_currency = :target_currency
|
|
)
|
|
WHERE a.family_id = :family_id
|
|
AND t.kind NOT IN ('funds_movement', 'one_time', 'cc_payment')
|
|
GROUP BY period, CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END
|
|
)
|
|
SELECT
|
|
classification,
|
|
ABS(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY total)) as median,
|
|
ABS(AVG(total)) as avg
|
|
FROM period_totals
|
|
GROUP BY classification;
|
|
SQL
|
|
end
|
|
end
|