1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-07-24 07:39:39 +02:00

Account::Entry Delegated Type (namespace updates part 7) (#923)

* Initial entryable models

* Update transfer and tests

* Update transaction controllers and tests

* Update sync process to use new entries model

* Get dashboard working again

* Update transfers, imports, and accounts to use Account::Entry

* Update system tests

* Consolidate transaction management into entries controller

* Add permitted partial key helper

* Move account transactions list to entries controller

* Delegate transaction entries search

* Move transfer relation to entry

* Update bulk transaction management flows to use entries

* Remove test code

* Test fix attempt

* Update demo data script

* Consolidate remaining transaction partials to entries

* Consolidate valuations controller to entries controller

* Lint fix

* Remove unused files, additional cleanup

* Add back valuation creation

* Make migrations fully reversible

* Stale routes cleanup

* Migrations reversible fix

* Move types to entryable concern

* Fix search when no entries found

* Remove more unused code
This commit is contained in:
Zach Gollwitzer 2024-07-01 10:49:43 -04:00 committed by GitHub
parent 320954282a
commit c3314e62d1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
105 changed files with 2150 additions and 1576 deletions

View file

@ -0,0 +1,91 @@
class Account::EntriesController < ApplicationController
layout "with_sidebar"
before_action :set_account
before_action :set_entry, only: %i[ edit update show destroy ]
def transactions
@transaction_entries = @account.entries.account_transactions.reverse_chronological
end
def valuations
@valuation_entries = @account.entries.account_valuations.reverse_chronological
end
def new
@entry = @account.entries.build.tap do |entry|
if params[:entryable_type]
entry.entryable = Account::Entryable.from_type(params[:entryable_type]).new
else
entry.entryable = Account::Valuation.new
end
end
end
def create
@entry = @account.entries.build(entry_params_with_defaults(entry_params))
if @entry.save
@entry.sync_account_later
redirect_to account_path(@account), notice: t(".success", name: @entry.entryable_name_short.upcase_first)
else
# TODO: this is not an ideal way to handle errors and should eventually be improved.
# See: https://github.com/hotwired/turbo-rails/pull/367
flash[:error] = @entry.errors.full_messages.to_sentence
redirect_to account_path(@account)
end
end
def edit
end
def update
@entry.update! entry_params
@entry.sync_account_later
respond_to do |format|
format.html { redirect_to account_entry_path(@account, @entry), notice: t(".success") }
format.turbo_stream { render turbo_stream: turbo_stream.replace(@entry) }
end
end
def show
end
def destroy
@entry.destroy!
@entry.sync_account_later
redirect_back_or_to account_url(@entry.account), notice: t(".success")
end
private
def set_account
@account = Current.family.accounts.find(params[:account_id])
end
def set_entry
@entry = @account.entries.find(params[:id])
end
def permitted_entryable_attributes
entryable_type = @entry ? @entry.entryable_class.to_s : params[:account_entry][:entryable_type]
case entryable_type
when "Account::Transaction"
[ :id, :notes, :excluded, :category_id, :merchant_id, tag_ids: [] ]
else
[ :id ]
end
end
def entry_params
params.require(:account_entry)
.permit(:name, :date, :amount, :currency, :entryable_type, entryable_attributes: permitted_entryable_attributes)
end
# entryable_type is required here because Rails expects both of these params in this exact order (potential upstream bug)
def entry_params_with_defaults(params)
params.with_defaults(entryable_type: params[:entryable_type], entryable_attributes: {})
end
end

View file

@ -1,22 +0,0 @@
class Account::Transaction::RowsController < ApplicationController
before_action :set_transaction, only: %i[ show update ]
def show
end
def update
@transaction.update! transaction_params
redirect_to account_transaction_row_path(@transaction.account, @transaction)
end
private
def transaction_params
params.require(:transaction).permit(:category_id)
end
def set_transaction
@transaction = Current.family.accounts.find(params[:account_id]).transactions.find(params[:transaction_id])
end
end

View file

@ -1,6 +0,0 @@
class Account::Transaction::RulesController < ApplicationController
layout "with_sidebar"
def index
end
end

View file

@ -1,47 +0,0 @@
class Account::TransactionsController < ApplicationController
layout "with_sidebar"
before_action :set_account
before_action :set_transaction, only: %i[ show update destroy ]
def index
@transactions = @account.transactions.ordered
end
def show
end
def update
@transaction.update! transaction_params
@transaction.sync_account_later
respond_to do |format|
format.html { redirect_back_or_to account_transaction_path(@account, @transaction), notice: t(".success") }
format.turbo_stream { render turbo_stream: turbo_stream.replace(@transaction) }
end
end
def destroy
@transaction.destroy!
@transaction.sync_account_later
redirect_back_or_to account_url(@transaction.account), notice: t(".success")
end
private
def set_account
@account = Current.family.accounts.find(params[:account_id])
end
def set_transaction
@transaction = @account.transactions.find(params[:id])
end
def search_params
params.fetch(:q, {}).permit(:start_date, :end_date, :search, accounts: [], account_ids: [], categories: [], merchants: [])
end
def transaction_params
params.require(:account_transaction).permit(:name, :date, :amount, :currency, :notes, :excluded, :category_id, :merchant_id, tag_ids: [])
end
end

View file

@ -1,61 +0,0 @@
class Account::ValuationsController < ApplicationController
before_action :set_account
before_action :set_valuation, only: %i[ show edit update destroy ]
def new
@valuation = @account.valuations.new
end
def show
end
def create
@valuation = @account.valuations.build(valuation_params)
if @valuation.save
@valuation.sync_account_later
redirect_to account_path(@account), notice: "Valuation created"
else
# TODO: this is not an ideal way to handle errors and should eventually be improved.
# See: https://github.com/hotwired/turbo-rails/pull/367
flash[:error] = @valuation.errors.full_messages.to_sentence
redirect_to account_path(@account)
end
end
def edit
end
def update
if @valuation.update(valuation_params)
@valuation.sync_account_later
redirect_to account_path(@account), notice: t(".success")
else
# TODO: this is not an ideal way to handle errors and should eventually be improved.
# See: https://github.com/hotwired/turbo-rails/pull/367
flash[:error] = @valuation.errors.full_messages.to_sentence
redirect_to account_path(@account)
end
end
def destroy
@valuation.destroy!
@valuation.sync_account_later
redirect_to account_path(@account), notice: t(".success")
end
private
def set_account
@account = Current.family.accounts.find(params[:account_id])
end
def set_valuation
@valuation = @account.valuations.find(params[:id])
end
def valuation_params
params.require(:account_valuation).permit(:date, :value, :currency)
end
end

View file

@ -21,7 +21,7 @@ class PagesController < ApplicationController
@accounts = Current.family.accounts
@account_groups = @accounts.by_group(period: @period, currency: Current.family.currency)
@transactions = Current.family.transactions.limit(6).order(date: :desc)
@transaction_entries = Current.family.entries.account_transactions.limit(6).reverse_chronological
# TODO: Placeholders for trendlines
placeholder_series_data = 10.times.map do |i|

View file

@ -3,8 +3,8 @@ class TransactionsController < ApplicationController
def index
@q = search_params
result = Current.family.transactions.search(@q).ordered
@pagy, @transactions = pagy(result, items: params[:per_page] || "10")
result = Current.family.entries.account_transactions.search(@q).reverse_chronological
@pagy, @transaction_entries = pagy(result, items: params[:per_page] || "50")
@totals = {
count: result.select { |t| t.currency == Current.family.currency }.count,
@ -14,25 +14,26 @@ class TransactionsController < ApplicationController
end
def new
@transaction = Account::Transaction.new.tap do |txn|
@entry = Current.family.entries.new(entryable: Account::Transaction.new).tap do |e|
if params[:account_id]
txn.account = Current.family.accounts.find(params[:account_id])
e.account = Current.family.accounts.find(params[:account_id])
end
end
end
def create
@transaction = Current.family.accounts
.find(params[:transaction][:account_id])
.transactions
.create!(transaction_params.merge(amount: amount))
@entry = Current.family
.accounts
.find(params[:account_entry][:account_id])
.entries
.create!(transaction_entry_params.merge(amount: amount))
@transaction.sync_account_later
redirect_back_or_to account_path(@transaction.account), notice: t(".success")
@entry.sync_account_later
redirect_back_or_to account_path(@entry.account), notice: t(".success")
end
def bulk_delete
destroyed = Current.family.transactions.destroy_by(id: bulk_delete_params[:transaction_ids])
destroyed = Current.family.entries.destroy_by(id: bulk_delete_params[:entry_ids])
redirect_back_or_to transactions_url, notice: t(".success", count: destroyed.count)
end
@ -40,19 +41,18 @@ class TransactionsController < ApplicationController
end
def bulk_update
transactions = Current.family.transactions.where(id: bulk_update_params[:transaction_ids])
if transactions.update_all(bulk_update_params.except(:transaction_ids).to_h.compact_blank!)
redirect_back_or_to transactions_url, notice: t(".success", count: transactions.count)
else
flash.now[:error] = t(".failure")
render :index, status: :unprocessable_entity
end
updated = Current.family
.entries
.where(id: bulk_update_params[:entry_ids])
.bulk_update!(bulk_update_params)
redirect_back_or_to transactions_url, notice: t(".success", count: updated)
end
def mark_transfers
Current.family
.transactions
.where(id: bulk_update_params[:transaction_ids])
.entries
.where(id: bulk_update_params[:entry_ids])
.mark_transfers!
redirect_back_or_to transactions_url, notice: t(".success")
@ -60,40 +60,45 @@ class TransactionsController < ApplicationController
def unmark_transfers
Current.family
.transactions
.where(id: bulk_update_params[:transaction_ids])
.entries
.where(id: bulk_update_params[:entry_ids])
.update_all marked_as_transfer: false
redirect_back_or_to transactions_url, notice: t(".success")
end
def rules
end
private
def amount
if nature.income?
transaction_params[:amount].to_d * -1
transaction_entry_params[:amount].to_d * -1
else
transaction_params[:amount].to_d
transaction_entry_params[:amount].to_d
end
end
def nature
params[:transaction][:nature].to_s.inquiry
params[:account_entry][:nature].to_s.inquiry
end
def bulk_delete_params
params.require(:bulk_delete).permit(transaction_ids: [])
params.require(:bulk_delete).permit(entry_ids: [])
end
def bulk_update_params
params.require(:bulk_update).permit(:date, :notes, :excluded, :category_id, :merchant_id, transaction_ids: [])
params.require(:bulk_update).permit(:date, :notes, :category_id, :merchant_id, entry_ids: [])
end
def search_params
params.fetch(:q, {}).permit(:start_date, :end_date, :search, accounts: [], account_ids: [], categories: [], merchants: [])
end
def transaction_params
params.require(:transaction).permit(:name, :date, :amount, :currency, :category_id, tag_ids: [])
def transaction_entry_params
params.require(:account_entry)
.permit(:name, :date, :amount, :currency, :entryable_type, entryable_attributes: [ :category_id ])
.with_defaults(entryable_type: "Account::Transaction", entryable_attributes: {})
end
end

View file

@ -0,0 +1,39 @@
module Account::EntriesHelper
def permitted_entryable_partial_path(entry, relative_partial_path)
"account/entries/entryables/#{permitted_entryable_key(entry)}/#{relative_partial_path}"
end
def unconfirmed_transfer?(entry)
entry.marked_as_transfer? && entry.transfer.nil?
end
def transfer_entries(entries)
transfers = entries.select { |e| e.transfer_id.present? }
transfers.map(&:transfer).uniq
end
def entry_icon(entry, is_oldest: false)
if is_oldest
"keyboard"
elsif entry.trend.direction.up?
"arrow-up"
elsif entry.trend.direction.down?
"arrow-down"
else
"minus"
end
end
def entry_style(entry, is_oldest: false)
color = is_oldest ? "#D444F1" : entry.trend.color
mixed_hex_styles(color)
end
private
def permitted_entryable_key(entry)
permitted_entryable_paths = %w[transaction valuation]
entry.entryable_name_short.presence_in(permitted_entryable_paths)
end
end

View file

@ -1,24 +0,0 @@
module Account::TransactionsHelper
def unconfirmed_transfer?(transaction)
transaction.marked_as_transfer && transaction.transfer.nil?
end
def group_transactions_by_date(transactions)
grouped_by_date = {}
transactions.each do |transaction|
if transaction.transfer
transfer_date = transaction.transfer.inflow_transaction.date
grouped_by_date[transfer_date] ||= { transactions: [], transfers: [] }
unless grouped_by_date[transfer_date][:transfers].include?(transaction.transfer)
grouped_by_date[transfer_date][:transfers] << transaction.transfer
end
else
grouped_by_date[transaction.date] ||= { transactions: [], transfers: [] }
grouped_by_date[transaction.date][:transactions] << transaction
end
end
grouped_by_date
end
end

View file

@ -1,23 +0,0 @@
module Account::ValuationsHelper
def valuation_icon(valuation)
if valuation.oldest?
"keyboard"
elsif valuation.trend.direction.up?
"arrow-up"
elsif valuation.trend.direction.down?
"arrow-down"
else
"minus"
end
end
def valuation_style(valuation)
color = valuation.oldest? ? "#D444F1" : valuation.trend.color
<<-STYLE.strip
background-color: color-mix(in srgb, #{color} 5%, white);
border-color: color-mix(in srgb, #{color} 10%, white);
color: #{color};
STYLE
end
end

View file

@ -65,6 +65,20 @@ module ApplicationHelper
end
end
def mixed_hex_styles(hex)
color = hex || "#1570EF" # blue-600
<<-STYLE.strip
background-color: color-mix(in srgb, #{color} 5%, white);
border-color: color-mix(in srgb, #{color} 10%, white);
color: #{color};
STYLE
end
def circle_logo(name, hex: nil, size: "md")
render partial: "shared/circle_logo", locals: { name: name, hex: hex, size: size }
end
def return_to_path(params, fallback = root_path)
uri = URI.parse(params[:return_to] || fallback)
uri.relative? ? uri.path : root_path
@ -123,7 +137,7 @@ module ApplicationHelper
ActiveSupport::NumberHelper.number_to_delimited(money.amount.round(options[:precision] || 0), { delimiter: options[:delimiter], separator: options[:separator] })
end
def totals_by_currency(collection:, money_method:, separator: " | ", negate: false, options: {})
def totals_by_currency(collection:, money_method:, separator: " | ", negate: false)
collection.group_by(&:currency)
.transform_values { |item| negate ? item.sum(&money_method) * -1 : item.sum(&money_method) }
.map { |_currency, money| format_money(money) }

View file

@ -11,6 +11,22 @@ module FormsHelper
end
end
def selectable_categories
Current.family.categories.alphabetically
end
def selectable_merchants
Current.family.merchants.alphabetically
end
def selectable_accounts
Current.family.accounts.alphabetically
end
def selectable_tags
Current.family.tags.alphabetically.pluck(:name, :id)
end
private
def radio_tab_contents(label:, icon:)
tag.div(class: "flex px-4 py-1 rounded-lg items-center space-x-2 justify-center text-gray-400 group-has-[:checked]:bg-white group-has-[:checked]:text-gray-800 group-has-[:checked]:shadow-sm") do

View file

@ -1,4 +1,4 @@
module Account::Transaction::SearchesHelper
module TransactionsHelper
def transaction_search_filters
[
{ key: "account_filter", name: "Account", icon: "layers" },

View file

@ -25,7 +25,7 @@ export default class extends Controller {
submitBulkRequest(e) {
const form = e.target.closest("form");
const scope = e.params.scope
this.#addHiddenFormInputsForSelectedIds(form, `${scope}[transaction_ids][]`, this.selectedIdsValue)
this.#addHiddenFormInputsForSelectedIds(form, `${scope}[entry_ids][]`, this.selectedIdsValue)
form.requestSubmit()
}

View file

@ -8,14 +8,17 @@ class Account < ApplicationRecord
belongs_to :family
belongs_to :institution, optional: true
has_many :entries, dependent: :destroy, class_name: "Account::Entry"
has_many :transactions, through: :entries, source: :entryable, source_type: "Account::Transaction"
has_many :valuations, through: :entries, source: :entryable, source_type: "Account::Valuation"
has_many :balances, dependent: :destroy
has_many :valuations, dependent: :destroy
has_many :transactions, dependent: :destroy
has_many :imports, dependent: :destroy
monetize :balance
enum :status, { ok: "ok", syncing: "syncing", error: "error" }, validate: true
enum :classification, { asset: "asset", liability: "liability" }, validate: { allow_nil: true }
scope :active, -> { where(is_active: true) }
scope :assets, -> { where(classification: "asset") }
@ -35,8 +38,7 @@ class Account < ApplicationRecord
# e.g. Wise, Revolut accounts that have transactions in multiple currencies
def multi_currency?
currencies = [ valuations.pluck(:currency), transactions.pluck(:currency) ].flatten.uniq
currencies.count > 1
entries.select(:currency).distinct.count > 1
end
# e.g. Accounts denominated in currency other than family currency
@ -44,16 +46,6 @@ class Account < ApplicationRecord
currency != family.currency
end
def self.by_provider
# TODO: When 3rd party providers are supported, dynamically load all providers and their accounts
[ { name: "Manual accounts", accounts: all.order(balance: :desc).group_by(&:accountable_type) } ]
end
def self.some_syncing?
exists?(status: "syncing")
end
def series(period: Period.all, currency: self.currency)
balance_series = balances.in_period(period).where(currency: Money::Currency.new(currency).iso_code)
@ -93,11 +85,19 @@ class Account < ApplicationRecord
account.accountable = Accountable.from_type(attributes[:accountable_type])&.new
# Always build the initial valuation
account.valuations.build(date: Date.current, value: attributes[:balance], currency: account.currency)
account.entries.build \
date: Date.current,
amount: attributes[:balance],
currency: account.currency,
entryable: Account::Valuation.new
# Conditionally build the optional start valuation
if start_date.present? && start_balance.present?
account.valuations.build(date: start_date, value: start_balance, currency: account.currency)
account.entries.build \
date: start_date,
amount: start_balance,
currency: account.currency,
entryable: Account::Valuation.new
end
account.save!

View file

@ -1,123 +1,115 @@
class Account::Balance::Calculator
attr_reader :daily_balances, :errors, :warnings
attr_reader :errors, :warnings
def initialize(account, options = {})
@daily_balances = []
@errors = []
@warnings = []
@account = account
@calc_start_date = [ options[:calc_start_date], @account.effective_start_date ].compact.max
def initialize(account, options = {})
@errors = []
@warnings = []
@account = account
@calc_start_date = calculate_sync_start(options[:calc_start_date])
end
def daily_balances
@daily_balances ||= calculate_daily_balances
end
private
attr_reader :calc_start_date, :account
def calculate_sync_start(provided_start_date = nil)
if account.balances.any?
[ provided_start_date, account.effective_start_date ].compact.max
else
account.effective_start_date
end
end
def calculate
prior_balance = implied_start_balance
def calculate_daily_balances
prior_balance = nil
calculated_balances = ((@calc_start_date + 1.day)..Date.current).map do |date|
valuation = normalized_valuations.find { |v| v["date"] == date }
calculated_balances = (calc_start_date..Date.current).map do |date|
valuation_entry = find_valuation_entry(date)
if valuation
current_balance = valuation["value"]
if valuation_entry
current_balance = valuation_entry.amount
elsif prior_balance.nil?
current_balance = implied_start_balance
else
txn_flows = transaction_flows(date)
txn_entries = syncable_transaction_entries.select { |e| e.date == date }
txn_flows = transaction_flows(txn_entries)
current_balance = prior_balance - txn_flows
end
prior_balance = current_balance
{ date:, balance: current_balance, currency: @account.currency, updated_at: Time.current }
{ date:, balance: current_balance, currency: account.currency, updated_at: Time.current }
end
@daily_balances = [
{ date: @calc_start_date, balance: implied_start_balance, currency: @account.currency, updated_at: Time.current },
*calculated_balances
]
if @account.foreign_currency?
converted_balances = convert_balances_to_family_currency
@daily_balances.concat(converted_balances)
if account.foreign_currency?
calculated_balances.concat(convert_balances_to_family_currency(calculated_balances))
end
self
calculated_balances
end
private
def convert_balances_to_family_currency
rates = ExchangeRate.get_rates(
@account.currency,
@account.family.currency,
@calc_start_date..Date.current
).to_a
def syncable_entries
@entries ||= account.entries.where("date >= ?", calc_start_date).to_a
end
# Abort conversion if some required rates are missing
if rates.length != @daily_balances.length
@errors << :sync_message_missing_rates
return []
end
def syncable_transaction_entries
@syncable_transaction_entries ||= syncable_entries.select { |e| e.account_transaction? }
end
@daily_balances.map.with_index do |balance, index|
converted_balance = balance[:balance] * rates[index].rate
{ date: balance[:date], balance: converted_balance, currency: @account.family.currency, updated_at: Time.current }
end
def find_valuation_entry(date)
syncable_entries.find { |entry| entry.date == date && entry.account_valuation? }
end
def transaction_flows(transaction_entries)
converted_entries = transaction_entries.map { |entry| convert_entry_to_account_currency(entry) }.compact
flows = converted_entries.sum(&:amount)
flows *= -1 if account.liability?
flows
end
def convert_balances_to_family_currency(balances)
rates = ExchangeRate.get_rates(
account.currency,
account.family.currency,
calc_start_date..Date.current
).to_a
# Abort conversion if some required rates are missing
if rates.length != balances.length
@errors << :sync_message_missing_rates
return []
end
# For calculation, all transactions and valuations need to be normalized to the same currency (the account's primary currency)
def normalize_entries_to_account_currency(entries, value_key)
grouped_entries = entries.group_by(&:currency)
normalized_entries = []
balances.map.with_index do |balance, index|
converted_balance = balance[:balance] * rates[index].rate
{ date: balance[:date], balance: converted_balance, currency: account.family.currency, updated_at: Time.current }
end
end
grouped_entries.each do |currency, entries|
if currency != @account.currency
dates = entries.map(&:date).uniq
rates = ExchangeRate.get_rates(currency, @account.currency, dates).to_a
if rates.length != dates.length
@errors << :sync_message_missing_rates
else
entries.each do |entry|
## There can be several entries on the same date so we cannot rely on indeces
rate = rates.find { |rate| rate.date == entry.date }
value = entry.send(value_key)
value *= rate.rate
normalized_entries << entry.attributes.merge(value_key.to_s => value, "currency" => currency)
end
end
else
normalized_entries.concat(entries)
end
end
# Multi-currency accounts have transactions in many currencies
def convert_entry_to_account_currency(entry)
return entry if entry.currency == account.currency
normalized_entries
converted_entry = entry.dup
rate = ExchangeRate.find_rate(from: entry.currency, to: account.currency, date: entry.date)
unless rate
@errors << :sync_message_missing_rates
return nil
end
def normalized_valuations
@normalized_valuations ||= normalize_entries_to_account_currency(@account.valuations.where("date >= ?", @calc_start_date).order(:date).select(:date, :value, :currency), :value)
end
converted_entry.currency = account.currency
converted_entry.amount = entry.amount * rate.rate
converted_entry
end
def normalized_transactions
@normalized_transactions ||= normalize_entries_to_account_currency(@account.transactions.where("date >= ?", @calc_start_date).order(:date).select(:date, :amount, :currency), :amount)
end
def transaction_flows(date)
flows = normalized_transactions.select { |t| t["date"] == date }.sum { |t| t["amount"] }
flows *= -1 if @account.classification == "liability"
flows
end
def implied_start_balance
if @calc_start_date > @account.effective_start_date
return @account.balance_on(@calc_start_date)
end
oldest_valuation_date = normalized_valuations.first&.date
oldest_transaction_date = normalized_transactions.first&.date
oldest_entry_date = [ oldest_valuation_date, oldest_transaction_date ].compact.min
if oldest_entry_date.present? && oldest_entry_date == oldest_valuation_date
oldest_valuation = normalized_valuations.find { |v| v["date"] == oldest_valuation_date }
oldest_valuation["value"].to_d
else
net_transaction_flows = normalized_transactions.sum { |t| t["amount"].to_d }
net_transaction_flows *= -1 if @account.classification == "liability"
@account.balance.to_d + net_transaction_flows
end
end
def implied_start_balance
transaction_entries = syncable_transaction_entries.select { |e| e.date > calc_start_date }
account.balance.to_d + transaction_flows(transaction_entries)
end
end

196
app/models/account/entry.rb Normal file
View file

@ -0,0 +1,196 @@
class Account::Entry < ApplicationRecord
include Monetizable
monetize :amount
belongs_to :account
belongs_to :transfer, optional: true
delegated_type :entryable, types: Account::Entryable::TYPES, dependent: :destroy
accepts_nested_attributes_for :entryable
validates :date, :amount, :currency, presence: true
validates :date, uniqueness: { scope: [ :account_id, :entryable_type ] }, if: -> { account_valuation? }
scope :chronological, -> { order(:date, :created_at) }
scope :reverse_chronological, -> { order(date: :desc, created_at: :desc) }
scope :without_transfers, -> { where(marked_as_transfer: false) }
scope :with_converted_amount, ->(currency) {
# Join with exchange rates to convert the amount to the given currency
# If no rate is available, exclude the transaction from the results
select(
"account_entries.*",
"account_entries.amount * COALESCE(er.rate, 1) AS converted_amount"
)
.joins(sanitize_sql_array([ "LEFT JOIN exchange_rates er ON account_entries.date = er.date AND account_entries.currency = er.base_currency AND er.converted_currency = ?", currency ]))
.where("er.rate IS NOT NULL OR account_entries.currency = ?", currency)
}
def sync_account_later
if destroyed?
sync_start_date = previous_entry&.date
else
sync_start_date = [ date_previously_was, date ].compact.min
end
account.sync_later(sync_start_date)
end
def inflow?
amount <= 0 && account_transaction?
end
def outflow?
amount > 0 && account_transaction?
end
def first_of_type?
first_entry = account
.entries
.where("entryable_type = ?", entryable_type)
.order(:date)
.first
first_entry&.id == id
end
def entryable_name_short
entryable_type.demodulize.underscore
end
def trend
@trend ||= create_trend
end
class << self
def daily_totals(entries, currency, period: Period.last_30_days)
# Sum spending and income for each day in the period with the given currency
select(
"gs.date",
"COALESCE(SUM(converted_amount) FILTER (WHERE converted_amount > 0), 0) AS spending",
"COALESCE(SUM(-converted_amount) FILTER (WHERE converted_amount < 0), 0) AS income"
)
.from(entries.with_converted_amount(currency), :e)
.joins(sanitize_sql([ "RIGHT JOIN generate_series(?, ?, interval '1 day') AS gs(date) ON e.date = gs.date", period.date_range.first, period.date_range.last ]))
.group("gs.date")
end
def daily_rolling_totals(entries, currency, period: Period.last_30_days)
# Extend the period to include the rolling window
period_with_rolling = period.extend_backward(period.date_range.count.days)
# Aggregate the rolling sum of spending and income based on daily totals
rolling_totals = from(daily_totals(entries, currency, period: period_with_rolling))
.select(
"*",
sanitize_sql_array([ "SUM(spending) OVER (ORDER BY date RANGE BETWEEN INTERVAL ? PRECEDING AND CURRENT ROW) as rolling_spend", "#{period.date_range.count} days" ]),
sanitize_sql_array([ "SUM(income) OVER (ORDER BY date RANGE BETWEEN INTERVAL ? PRECEDING AND CURRENT ROW) as rolling_income", "#{period.date_range.count} days" ])
)
.order(:date)
# Trim the results to the original period
select("*").from(rolling_totals).where("date >= ?", period.date_range.first)
end
def mark_transfers!
update_all marked_as_transfer: true
# Attempt to "auto match" and save a transfer if 2 transactions selected
Account::Transfer.new(entries: all).save if all.count == 2
end
def bulk_update!(bulk_update_params)
bulk_attributes = {
date: bulk_update_params[:date],
entryable_attributes: {
notes: bulk_update_params[:notes],
category_id: bulk_update_params[:category_id],
merchant_id: bulk_update_params[:merchant_id]
}.compact_blank
}.compact_blank
return 0 if bulk_attributes.blank?
transaction do
all.each do |entry|
bulk_attributes[:entryable_attributes][:id] = entry.entryable_id if bulk_attributes[:entryable_attributes].present?
entry.update! bulk_attributes
end
end
all.size
end
def income_total(currency = "USD")
account_transactions.includes(:entryable)
.where("account_entries.amount <= 0")
.where("account_entries.currency = ?", currency)
.reject { |e| e.marked_as_transfer? }
.sum(&:amount_money)
end
def expense_total(currency = "USD")
account_transactions.includes(:entryable)
.where("account_entries.amount > 0")
.where("account_entries.currency = ?", currency)
.reject { |e| e.marked_as_transfer? }
.sum(&:amount_money)
end
def search(params)
query = all
query = query.where("account_entries.name ILIKE ?", "%#{params[:search]}%") if params[:search].present?
query = query.where("account_entries.date >= ?", params[:start_date]) if params[:start_date].present?
query = query.where("account_entries.date <= ?", params[:end_date]) if params[:end_date].present?
if params[:accounts].present? || params[:account_ids].present?
query = query.joins(:account)
end
query = query.where(accounts: { name: params[:accounts] }) if params[:accounts].present?
query = query.where(accounts: { id: params[:account_ids] }) if params[:account_ids].present?
# Search attributes on each entryable to further refine results
entryable_ids = entryable_search(params)
query = query.where(entryable_id: entryable_ids) unless entryable_ids.nil?
query
end
private
def entryable_search(params)
entryable_ids = []
entryable_search_performed = false
Account::Entryable::TYPES.map(&:constantize).each do |entryable|
next unless entryable.requires_search?(params)
entryable_search_performed = true
entryable_ids += entryable.search(params).pluck(:id)
end
return nil unless entryable_search_performed
entryable_ids
end
end
private
def previous_entry
@previous_entry ||= account
.entries
.where("date < ?", date)
.where("entryable_type = ?", entryable_type)
.order(date: :desc)
.first
end
def create_trend
TimeSeries::Trend.new \
current: amount_money,
previous: previous_entry&.amount_money,
favorable_direction: account.favorable_direction
end
end

View file

@ -0,0 +1,13 @@
module Account::Entryable
extend ActiveSupport::Concern
TYPES = %w[ Account::Valuation Account::Transaction ]
def self.from_type(entryable_type)
entryable_type.presence_in(TYPES).constantize
end
included do
has_one :entry, as: :entryable, touch: true
end
end

View file

@ -8,17 +8,22 @@ module Account::Syncable
def sync(start_date = nil)
update!(status: "syncing")
sync_exchange_rates
if multi_currency? || foreign_currency?
sync_exchange_rates
end
calc_start_date = start_date - 1.day if start_date.present? && self.balance_on(start_date - 1.day).present?
calculator = Account::Balance::Calculator.new(self, { calc_start_date: start_date })
calculator = Account::Balance::Calculator.new(self, { calc_start_date: })
calculator.calculate
self.balances.upsert_all(calculator.daily_balances, unique_by: :index_account_balances_on_account_id_date_currency_unique)
self.balances.where("date < ?", effective_start_date).delete_all
new_balance = calculator.daily_balances.select { |b| b[:currency] == self.currency }.last[:balance]
update!(status: "ok", last_sync_date: Date.today, balance: new_balance, sync_errors: calculator.errors, sync_warnings: calculator.warnings)
update! \
status: "ok",
last_sync_date: Date.current,
balance: new_balance,
sync_errors: calculator.errors,
sync_warnings: calculator.warnings
rescue => e
update!(status: "error", sync_errors: [ :sync_message_unknown_error ])
logger.error("Failed to sync account #{id}: #{e.message}")
@ -37,10 +42,7 @@ module Account::Syncable
# The earliest date we can calculate a balance for
def effective_start_date
first_valuation_date = self.valuations.order(:date).pluck(:date).first
first_transaction_date = self.transactions.order(:date).pluck(:date).first
[ first_valuation_date, first_transaction_date&.prev_day ].compact.min || Date.current
@effective_start_date ||= entries.order(:date).first.try(:date) || Date.current
end
# Finds all the rate pairs that are required to calculate balances for an account and syncs them
@ -48,7 +50,7 @@ module Account::Syncable
rate_candidates = []
if multi_currency?
transactions_in_foreign_currency = self.transactions.where.not(currency: self.currency).pluck(:currency, :date).uniq
transactions_in_foreign_currency = self.entries.where.not(currency: self.currency).pluck(:currency, :date).uniq
transactions_in_foreign_currency.each do |currency, date|
rate_candidates << { date: date, from_currency: currency, to_currency: self.currency }
end
@ -60,6 +62,8 @@ module Account::Syncable
end
end
return if rate_candidates.blank?
existing_rates = ExchangeRate.where(
base_currency: rate_candidates.map { |rc| rc[:from_currency] },
converted_currency: rate_candidates.map { |rc| rc[:to_currency] },

View file

@ -1,118 +1,32 @@
class Account::Transaction < ApplicationRecord
include Monetizable
include Account::Entryable
monetize :amount
belongs_to :account
belongs_to :transfer, optional: true, class_name: "Account::Transfer"
belongs_to :category, optional: true
belongs_to :merchant, optional: true
has_many :taggings, as: :taggable, dependent: :destroy
has_many :tags, through: :taggings
accepts_nested_attributes_for :taggings, allow_destroy: true
validates :name, :date, :amount, :account, presence: true
scope :ordered, -> { order(date: :desc) }
scope :active, -> { where(excluded: false) }
scope :inflows, -> { where("amount <= 0") }
scope :outflows, -> { where("amount > 0") }
scope :by_name, ->(name) { where("account_transactions.name ILIKE ?", "%#{name}%") }
scope :with_categories, ->(categories) { joins(:category).where(categories: { name: categories }) }
scope :with_accounts, ->(accounts) { joins(:account).where(accounts: { name: accounts }) }
scope :with_account_ids, ->(account_ids) { joins(:account).where(accounts: { id: account_ids }) }
scope :with_merchants, ->(merchants) { joins(:merchant).where(merchants: { name: merchants }) }
scope :on_or_after_date, ->(date) { where("account_transactions.date >= ?", date) }
scope :on_or_before_date, ->(date) { where("account_transactions.date <= ?", date) }
scope :with_converted_amount, ->(currency = Current.family.currency) {
# Join with exchange rates to convert the amount to the given currency
# If no rate is available, exclude the transaction from the results
select(
"account_transactions.*",
"account_transactions.amount * COALESCE(er.rate, 1) AS converted_amount"
)
.joins(sanitize_sql_array([ "LEFT JOIN exchange_rates er ON account_transactions.date = er.date AND account_transactions.currency = er.base_currency AND er.converted_currency = ?", currency ]))
.where("er.rate IS NOT NULL OR account_transactions.currency = ?", currency)
}
def inflow?
amount <= 0
end
def outflow?
amount > 0
end
def transfer?
marked_as_transfer
end
def sync_account_later
if destroyed?
sync_start_date = previous_transaction_date
else
sync_start_date = [ date_previously_was, date ].compact.min
end
account.sync_later(sync_start_date)
end
class << self
def income_total(currency = "USD")
inflows.reject(&:transfer?).select { |t| t.currency == currency }.sum(&:amount_money)
end
def expense_total(currency = "USD")
outflows.reject(&:transfer?).select { |t| t.currency == currency }.sum(&:amount_money)
end
def mark_transfers!
update_all marked_as_transfer: true
# Attempt to "auto match" and save a transfer if 2 transactions selected
Account::Transfer.new(transactions: all).save if all.count == 2
end
def daily_totals(transactions, period: Period.last_30_days, currency: Current.family.currency)
# Sum spending and income for each day in the period with the given currency
select(
"gs.date",
"COALESCE(SUM(converted_amount) FILTER (WHERE converted_amount > 0), 0) AS spending",
"COALESCE(SUM(-converted_amount) FILTER (WHERE converted_amount < 0), 0) AS income"
)
.from(transactions.with_converted_amount(currency).where(marked_as_transfer: false), :t)
.joins(sanitize_sql([ "RIGHT JOIN generate_series(?, ?, interval '1 day') AS gs(date) ON t.date = gs.date", period.date_range.first, period.date_range.last ]))
.group("gs.date")
end
def daily_rolling_totals(transactions, period: Period.last_30_days, currency: Current.family.currency)
# Extend the period to include the rolling window
period_with_rolling = period.extend_backward(period.date_range.count.days)
# Aggregate the rolling sum of spending and income based on daily totals
rolling_totals = from(daily_totals(transactions, period: period_with_rolling, currency: currency))
.select(
"*",
sanitize_sql_array([ "SUM(spending) OVER (ORDER BY date RANGE BETWEEN INTERVAL ? PRECEDING AND CURRENT ROW) as rolling_spend", "#{period.date_range.count} days" ]),
sanitize_sql_array([ "SUM(income) OVER (ORDER BY date RANGE BETWEEN INTERVAL ? PRECEDING AND CURRENT ROW) as rolling_income", "#{period.date_range.count} days" ])
)
.order("date")
# Trim the results to the original period
select("*").from(rolling_totals).where("date >= ?", period.date_range.first)
end
def search(params)
query = all.includes(:transfer)
query = query.by_name(params[:search]) if params[:search].present?
query = query.with_categories(params[:categories]) if params[:categories].present?
query = query.with_accounts(params[:accounts]) if params[:accounts].present?
query = query.with_account_ids(params[:account_ids]) if params[:account_ids].present?
query = query.with_merchants(params[:merchants]) if params[:merchants].present?
query = query.on_or_after_date(params[:start_date]) if params[:start_date].present?
query = query.on_or_before_date(params[:end_date]) if params[:end_date].present?
query = all
query = query.joins("LEFT JOIN categories ON categories.id = account_transactions.category_id").where(categories: { name: params[:categories] }) if params[:categories].present?
query = query.joins("LEFT JOIN merchants ON merchants.id = account_transactions.merchant_id").where(merchants: { name: params[:merchants] }) if params[:merchants].present?
query
end
def requires_search?(params)
searchable_keys.any? { |key| params.key?(key) }
end
private
def searchable_keys
%i[ categories merchants ]
end
end
private

View file

@ -1,21 +1,42 @@
class Account::Transfer < ApplicationRecord
has_many :transactions, dependent: :nullify
has_many :entries, dependent: :nullify
validate :net_zero_flows, if: :single_currency_transfer?
validate :transaction_count, :from_different_accounts, :all_transactions_marked
def date
outflow_transaction&.date
end
def amount_money
entries.first&.amount_money&.abs
end
def from_name
outflow_transaction&.account&.name
end
def to_name
inflow_transaction&.account&.name
end
def name
return nil unless from_name && to_name
I18n.t("account.transfer.name", from_account: from_name, to_account: to_name)
end
def inflow_transaction
transactions.find { |t| t.inflow? }
entries.find { |e| e.inflow? }
end
def outflow_transaction
transactions.find { |t| t.outflow? }
entries.find { |e| e.outflow? }
end
def destroy_and_remove_marks!
transaction do
transactions.each do |t|
t.update! marked_as_transfer: false
entries.each do |e|
e.update! marked_as_transfer: false
end
destroy!
@ -24,39 +45,52 @@ class Account::Transfer < ApplicationRecord
class << self
def build_from_accounts(from_account, to_account, date:, amount:, currency:, name:)
outflow = from_account.transactions.build(amount: amount.abs, currency: currency, date: date, name: name, marked_as_transfer: true)
inflow = to_account.transactions.build(amount: -amount.abs, currency: currency, date: date, name: name, marked_as_transfer: true)
outflow = from_account.entries.build \
amount: amount.abs,
currency: currency,
date: date,
name: name,
marked_as_transfer: true,
entryable: Account::Transaction.new
new transactions: [ outflow, inflow ]
inflow = to_account.entries.build \
amount: amount.abs * -1,
currency: currency,
date: date,
name: name,
marked_as_transfer: true,
entryable: Account::Transaction.new
new entries: [ outflow, inflow ]
end
end
private
def single_currency_transfer?
transactions.map(&:currency).uniq.size == 1
entries.map { |e| e.currency }.uniq.size == 1
end
def transaction_count
unless transactions.size == 2
errors.add :transactions, "must have exactly 2 transactions"
unless entries.size == 2
errors.add :entries, "must have exactly 2 entries"
end
end
def from_different_accounts
accounts = transactions.map(&:account_id).uniq
errors.add :transactions, "must be from different accounts" if accounts.size < transactions.size
accounts = entries.map { |e| e.account_id }.uniq
errors.add :entries, "must be from different accounts" if accounts.size < entries.size
end
def net_zero_flows
unless transactions.sum(&:amount).zero?
unless entries.sum(&:amount).zero?
errors.add :transactions, "must have an inflow and outflow that net to zero"
end
end
def all_transactions_marked
unless transactions.all?(&:marked_as_transfer)
errors.add :transactions, "must be marked as transfer"
unless entries.all?(&:marked_as_transfer)
errors.add :entries, "must be marked as transfer"
end
end
end

View file

@ -1,48 +1,13 @@
class Account::Valuation < ApplicationRecord
include Monetizable
include Account::Entryable
monetize :value
belongs_to :account
validates :account, :date, :value, presence: true
validates :date, uniqueness: { scope: :account_id }
scope :chronological, -> { order(:date) }
scope :reverse_chronological, -> { order(date: :desc) }
def trend
@trend ||= create_trend
end
def oldest?
account.valuations.chronological.limit(1).pluck(:date).first == self.date
end
def sync_account_later
if destroyed?
sync_start_date = previous_valuation&.date
else
sync_start_date = [ date_previously_was, date ].compact.min
class << self
def search(_params)
all
end
account.sync_later(sync_start_date)
def requires_search?(_params)
false
end
end
private
def previous_valuation
@previous_valuation ||= self.account
.valuations
.where("date < ?", date)
.order(date: :desc)
.first
end
def create_trend
TimeSeries::Trend.new \
current: self.value,
previous: previous_valuation&.value,
favorable_direction: account.favorable_direction
end
end

View file

@ -6,7 +6,7 @@ module Monetizable
fields.each do |field|
define_method("#{field}_money") do
value = self.send(field)
value.nil? ? nil : Money.new(value, currency)
value.nil? ? nil : Money.new(value, currency || Money.default_currency)
end
end
end

View file

@ -3,7 +3,8 @@ class Family < ApplicationRecord
has_many :tags, dependent: :destroy
has_many :accounts, dependent: :destroy
has_many :institutions, dependent: :destroy
has_many :transactions, through: :accounts, class_name: "Account::Transaction"
has_many :transactions, through: :accounts
has_many :entries, through: :accounts
has_many :imports, through: :accounts
has_many :categories, dependent: :destroy
has_many :merchants, dependent: :destroy
@ -34,17 +35,18 @@ class Family < ApplicationRecord
def snapshot_account_transactions
period = Period.last_30_days
results = accounts.active.joins(:transactions)
.select(
"accounts.*",
"COALESCE(SUM(amount) FILTER (WHERE amount > 0), 0) AS spending",
"COALESCE(SUM(-amount) FILTER (WHERE amount < 0), 0) AS income"
)
.where("account_transactions.date >= ?", period.date_range.begin)
.where("account_transactions.date <= ?", period.date_range.end)
.where("account_transactions.marked_as_transfer = ?", false)
.group("id")
.to_a
results = accounts.active.joins(:entries)
.select(
"accounts.*",
"COALESCE(SUM(account_entries.amount) FILTER (WHERE account_entries.amount > 0), 0) AS spending",
"COALESCE(SUM(-account_entries.amount) FILTER (WHERE account_entries.amount < 0), 0) AS income"
)
.where("account_entries.date >= ?", period.date_range.begin)
.where("account_entries.date <= ?", period.date_range.end)
.where("account_entries.marked_as_transfer = ?", false)
.where("account_entries.entryable_type = ?", "Account::Transaction")
.group("id")
.to_a
results.each do |r|
r.define_singleton_method(:savings_rate) do
@ -60,7 +62,8 @@ class Family < ApplicationRecord
end
def snapshot_transactions
rolling_totals = Account::Transaction.daily_rolling_totals(transactions, period: Period.last_30_days, currency: self.currency)
candidate_entries = entries.account_transactions.without_transfers
rolling_totals = Account::Entry.daily_rolling_totals(candidate_entries, self.currency, period: Period.last_30_days)
spending = []
income = []
@ -89,10 +92,6 @@ class Family < ApplicationRecord
}
end
def effective_start_date
accounts.active.joins(:balances).minimum("account_balances.date") || Date.current
end
def net_worth
assets - liabilities
end

View file

@ -111,7 +111,7 @@ class Import < ApplicationRecord
end
def generate_transactions
transactions = []
transaction_entries = []
category_cache = {}
tag_cache = {}
@ -126,18 +126,17 @@ class Import < ApplicationRecord
category = category_cache[category_name] ||= account.family.categories.find_or_initialize_by(name: category_name) if category_name.present?
txn = account.transactions.build \
entry = account.entries.build \
name: row["name"].presence || FALLBACK_TRANSACTION_NAME,
date: Date.iso8601(row["date"]),
category: category,
tags: tags,
amount: BigDecimal(row["amount"]) * -1, # User inputs amounts with opposite signage of our internal representation
currency: account.currency
currency: account.currency,
amount: BigDecimal(row["amount"]) * -1,
entryable: Account::Transaction.new(category: category, tags: tags)
transactions << txn
transaction_entries << entry
end
transactions
transaction_entries
end
def create_expected_fields

View file

@ -0,0 +1,4 @@
<%# locals: (entry:, **opts) %>
<%= turbo_frame_tag dom_id(entry) do %>
<%= render permitted_entryable_partial_path(entry, entry.entryable_name_short), entry: entry, **opts %>
<% end %>

View file

@ -0,0 +1,21 @@
<%# locals: (date:, entries:, selectable: true, **opts) %>
<div id="entry-group-<%= date %>" class="bg-gray-25 rounded-xl p-1 w-full" data-bulk-select-target="group">
<div class="py-2 px-4 flex items-center justify-between font-medium text-xs text-gray-500">
<div class="flex pl-0.5 items-center gap-4">
<% if selectable %>
<%= check_box_tag "#{date}_entries_selection",
class: ["maybe-checkbox maybe-checkbox--light", "hidden": entries.size == 0],
id: "selection_entry_#{date}",
data: { action: "bulk-select#toggleGroupSelection" } %>
<% end %>
<%= tag.span "#{date.strftime('%b %d, %Y')} · #{entries.size}" %>
</div>
<%= totals_by_currency(collection: entries, money_method: :amount_money, negate: true) %>
</div>
<div class="bg-white shadow-xs rounded-md border border-alpha-black-25 divide-y divide-alpha-black-50">
<%= render entries.reject { |e| e.transfer_id.present? }, selectable:, **opts %>
<%= render transfer_entries(entries), selectable:, **opts %>
</div>
</div>

View file

@ -1,6 +1,6 @@
<div class="fixed bottom-6 z-10 flex items-center justify-between rounded-xl bg-gray-900 px-4 text-sm text-white w-[420px] py-1.5">
<div class="flex items-center gap-2">
<%= check_box_tag "transaction_selection", 1, true, class: "maybe-checkbox maybe-checkbox--dark", data: { action: "bulk-select#deselectAll" } %>
<%= check_box_tag "entry_selection", 1, true, class: "maybe-checkbox maybe-checkbox--dark", data: { action: "bulk-select#deselectAll" } %>
<p data-bulk-select-target="selectionBarText"></p>
</div>
@ -19,7 +19,12 @@
accept: t(".mark_transfers_confirm"),
}
} do |f| %>
<button id="bulk-transfer-btn" type="button" data-bulk-select-scope-param="bulk_update" data-action="bulk-select#submitBulkRequest" class="p-1.5 group hover:bg-gray-700 flex items-center justify-center rounded-md" title="Mark as transfer">
<button id="bulk-transfer-btn"
type="button"
data-bulk-select-scope-param="bulk_update"
data-action="bulk-select#submitBulkRequest"
class="p-1.5 group hover:bg-gray-700 flex items-center justify-center rounded-md"
title="Mark as transfer">
<%= lucide_icon "arrow-right-left", class: "w-5 group-hover:text-white" %>
</button>
<% end %>

View file

@ -0,0 +1,3 @@
<%= turbo_frame_tag dom_id(@entry) do %>
<%= render permitted_entryable_partial_path(@entry, "edit"), entry: @entry %>
<% end %>

View file

@ -0,0 +1,113 @@
<%# locals: (entry:) %>
<% transaction, account = entry.account_transaction, entry.account %>
<%= drawer do %>
<div>
<header class="mb-4 space-y-1">
<div class="flex items-center gap-4">
<h3 class="font-medium">
<span class="text-2xl"><%= format_money -entry.amount_money %></span>
<span class="text-lg text-gray-500"><%= entry.currency %></span>
</h3>
<% if entry.marked_as_transfer? %>
<%= lucide_icon "arrow-left-right", class: "text-gray-500 mt-1 w-5 h-5" %>
<% end %>
</div>
<span class="text-sm text-gray-500"><%= entry.date.strftime("%A %d %B") %></span>
</header>
<div class="space-y-2">
<details class="group space-y-2" open>
<summary class="flex list-none items-center justify-between rounded-xl px-3 py-2 text-xs font-medium uppercase text-gray-500 bg-gray-25 focus-visible:outline-none">
<h4><%= t(".overview") %></h4>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<div class="pb-6">
<%= form_with model: [account, entry], url: account_entry_path(account, entry), html: { data: { controller: "auto-submit-form" } } do |f| %>
<div class="space-y-2">
<%= f.text_field :name, label: t(".name_label"), "data-auto-submit-form-target": "auto" %>
<%= f.date_field :date, label: t(".date_label"), max: Date.current, "data-auto-submit-form-target": "auto" %>
<%= f.fields_for :entryable do |ef| %>
<% unless entry.marked_as_transfer? %>
<%= ef.collection_select :category_id, selectable_categories, :id, :name, { prompt: t(".category_placeholder"), label: t(".category_label"), class: "text-gray-400" }, "data-auto-submit-form-target": "auto" %>
<%= ef.collection_select :merchant_id, selectable_merchants, :id, :name, { prompt: t(".merchant_placeholder"), label: t(".merchant_label"), class: "text-gray-400" }, "data-auto-submit-form-target": "auto" %>
<% end %>
<% end %>
<%= f.collection_select :account_id, selectable_accounts, :id, :name, { prompt: t(".account_placeholder"), label: t(".account_label"), class: "text-gray-500" }, { class: "form-field__input cursor-not-allowed text-gray-400", disabled: "disabled" } %>
</div>
<% end %>
</div>
</details>
<details class="group space-y-2" open>
<summary class="flex list-none items-center justify-between rounded-xl px-3 py-2 text-xs font-medium uppercase text-gray-500 bg-gray-25 focus-visible:outline-none">
<h4><%= t(".additional") %></h4>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<div class="pb-6 space-y-2">
<%= form_with model: [account, entry], url: account_entry_path(account, entry), html: { data: { controller: "auto-submit-form" } } do |f| %>
<%= f.fields_for :entryable do |ef| %>
<%= ef.select :tag_ids,
options_for_select(selectable_tags, transaction.tag_ids),
{
multiple: true,
label: t(".tags_label"),
class: "placeholder:text-gray-500"
},
"data-auto-submit-form-target": "auto" %>
<%= ef.text_area :notes, label: t(".note_label"), placeholder: t(".note_placeholder"), "data-auto-submit-form-target": "auto" %>
<% end %>
<% end %>
</div>
</details>
<details class="group space-y-2" open>
<summary class="flex list-none items-center justify-between rounded-xl px-3 py-2 text-xs font-medium uppercase text-gray-500 bg-gray-25 focus-visible:outline-none">
<h4><%= t(".settings") %></h4>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<div class="pb-6">
<%= form_with model: [account, entry], url: account_entry_path(account, entry), html: { class: "p-3 space-y-3", data: { controller: "auto-submit-form" } } do |f| %>
<%= f.fields_for :entryable do |ef| %>
<div class="flex cursor-pointer items-center gap-2 justify-between">
<div class="text-sm space-y-1">
<h4 class="text-gray-900"><%= t(".exclude_title") %></h4>
<p class="text-gray-500"><%= t(".exclude_subtitle") %></p>
</div>
<div class="relative inline-block select-none">
<%= ef.check_box :excluded, class: "sr-only peer", "data-auto-submit-form-target": "auto" %>
<label for="account_entry_entryable_attributes_excluded" class="maybe-switch"></label>
</div>
</div>
<% end %>
<% end %>
<% unless entry.marked_as_transfer? %>
<div class="flex items-center justify-between gap-2 p-3">
<div class="text-sm space-y-1">
<h4 class="text-gray-900"><%= t(".delete_title") %></h4>
<p class="text-gray-500"><%= t(".delete_subtitle") %></p>
</div>
<%= button_to t(".delete"),
account_entry_path(account, entry),
method: :delete,
class: "rounded-lg px-3 py-2 text-red-500 text-sm font-medium border border-alpha-black-200",
data: { turbo_confirm: true, turbo_frame: "_top" } %>
</div>
<% end %>
</div>
</details>
</div>
</div>
<% end %>

View file

@ -1,26 +1,27 @@
<%# locals: (transaction:, selectable: true, editable: true, short: false, show_tags: false) %>
<%= turbo_frame_tag dom_id(transaction), class: "grid grid-cols-12 items-center text-gray-900 text-sm font-medium p-4" do %>
<%# locals: (entry:, selectable: true, editable: true, short: false, show_tags: false, **opts) %>
<% transaction, account = entry.account_transaction, entry.account %>
<% name_col_span = transaction.transfer? ? "col-span-10" : short ? "col-span-6" : "col-span-4" %>
<div class="grid grid-cols-12 items-center text-gray-900 text-sm font-medium p-4">
<% name_col_span = entry.marked_as_transfer? ? "col-span-10" : short ? "col-span-6" : "col-span-4" %>
<div class="pr-10 flex items-center gap-4 <%= name_col_span %>">
<% if selectable %>
<%= check_box_tag dom_id(transaction, "selection"),
<%= check_box_tag dom_id(entry, "selection"),
class: "maybe-checkbox maybe-checkbox--light",
data: { id: transaction.id, "bulk-select-target": "row", action: "bulk-select#toggleRowSelection" } %>
data: { id: entry.id, "bulk-select-target": "row", action: "bulk-select#toggleRowSelection" } %>
<% end %>
<div class="max-w-full">
<%= content_tag :div, class: ["flex items-center gap-2"] do %>
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gray-600/5 text-gray-600">
<%= transaction.name[0].upcase %>
<%= entry.name[0].upcase %>
</div>
<div class="truncate text-gray-900">
<% if transaction.new_record? %>
<%= content_tag :p, transaction.name %>
<% if entry.new_record? %>
<%= content_tag :p, entry.name %>
<% else %>
<%= link_to transaction.name,
account_transaction_path(transaction.account, transaction),
<%= link_to entry.name,
account_entry_path(account, entry),
data: { turbo_frame: "drawer", turbo_prefetch: false },
class: "hover:underline hover:text-gray-800" %>
<% end %>
@ -28,7 +29,7 @@
<% end %>
</div>
<% if unconfirmed_transfer?(transaction) %>
<% if unconfirmed_transfer?(entry) %>
<% if editable %>
<%= form_with url: unmark_transfers_transactions_path, builder: ActionView::Helpers::FormBuilder, class: "flex items-center", data: {
turbo_confirm: {
@ -38,7 +39,7 @@
},
turbo_frame: "_top"
} do |f| %>
<%= f.hidden_field "bulk_update[transaction_ids][]", value: transaction.id %>
<%= f.hidden_field "bulk_update[entry_ids][]", value: entry.id %>
<%= f.button class: "flex items-center justify-center group", title: "Remove transfer" do %>
<%= lucide_icon "arrow-left-right", class: "group-hover:hidden text-gray-500 w-4 h-4" %>
<%= lucide_icon "unlink", class: "hidden group-hover:inline-block text-gray-900 w-4 h-4" %>
@ -50,7 +51,7 @@
<% end %>
</div>
<% unless transaction.transfer? %>
<% unless entry.marked_as_transfer? %>
<% unless short %>
<div class="flex items-center gap-1 <%= show_tags ? "col-span-6" : "col-span-3" %>">
<% if editable %>
@ -69,11 +70,11 @@
<% unless show_tags %>
<%= tag.div class: short ? "col-span-4" : "col-span-3" do %>
<% if transaction.new_record? %>
<%= tag.p transaction.account.name %>
<% if entry.new_record? %>
<%= tag.p account.name %>
<% else %>
<%= link_to transaction.account.name,
account_path(transaction.account, tab: "transactions"),
<%= link_to account.name,
account_path(account, tab: "transactions"),
data: { turbo_frame: "_top" },
class: "hover:underline" %>
<% end %>
@ -83,7 +84,7 @@
<div class="col-span-2 ml-auto">
<%= content_tag :p,
format_money(-transaction.amount_money),
class: ["text-green-600": transaction.inflow?] %>
format_money(-entry.amount_money),
class: ["text-green-600": entry.inflow?] %>
</div>
<% end %>
</div>

View file

@ -0,0 +1 @@
<%= render permitted_entryable_partial_path(entry, "form"), entry: entry %>

View file

@ -0,0 +1,24 @@
<%# locals: (entry:) %>
<%= form_with model: [entry.account, entry],
data: { turbo_frame: "_top" },
url: entry.new_record? ? account_entries_path(entry.account) : account_entry_path(entry.account, entry),
builder: ActionView::Helpers::FormBuilder do |f| %>
<div class="grid grid-cols-10 p-4 items-center">
<div class="col-span-7 flex items-center gap-4">
<div class="w-8 h-8 rounded-full p-1.5 flex items-center justify-center bg-gray-500/5">
<%= lucide_icon("pencil-line", class: "w-4 h-4 text-gray-500") %>
</div>
<div class="w-full flex items-center justify-between gap-2">
<%= f.date_field :date, required: "required", max: Date.current, class: "border border-alpha-black-200 bg-white rounded-lg shadow-xs min-w-[200px] px-3 py-1.5 text-gray-900 text-sm" %>
<%= f.number_field :amount, required: "required", placeholder: "0.00", step: "0.01", class: "bg-white border border-alpha-black-200 rounded-lg shadow-xs text-gray-900 text-sm px-3 py-1.5 text-right" %>
<%= f.hidden_field :currency, value: entry.account.currency %>
<%= f.hidden_field :entryable_type, value: entry.entryable_type %>
</div>
</div>
<div class="col-span-3 flex gap-2 justify-end items-center">
<%= link_to t(".cancel"), valuation_account_entries_path(entry.account), class: "text-sm text-gray-900 hover:text-gray-800 font-medium px-3 py-1.5" %>
<%= f.submit class: "bg-gray-50 rounded-lg font-medium px-3 py-1.5 cursor-pointer hover:bg-gray-100 text-sm" %>
</div>
</div>
<% end %>

View file

@ -0,0 +1,2 @@
<%= render permitted_entryable_partial_path(entry, "form"), entry: entry %>
<div class="h-px bg-alpha-black-50 ml-20 mr-4"></div>

View file

@ -0,0 +1 @@
<%= render permitted_entryable_partial_path(@entry, "valuation"), entry: @entry %>

View file

@ -1,36 +1,42 @@
<%= turbo_frame_tag dom_id(valuation) do %>
<%# locals: (entry:, **opts) %>
<% account = entry.account %>
<%= turbo_frame_tag dom_id(entry) do %>
<% is_oldest = entry.first_of_type? %>
<div class="p-4 grid grid-cols-10 items-center">
<div class="col-span-5 flex items-center gap-4">
<%= tag.div class: "w-8 h-8 rounded-full p-1.5 flex items-center justify-center", style: valuation_style(valuation).html_safe do %>
<%= lucide_icon valuation_icon(valuation), class: "w-4 h-4" %>
<%= tag.div class: "w-8 h-8 rounded-full p-1.5 flex items-center justify-center", style: entry_style(entry, is_oldest:).html_safe do %>
<%= lucide_icon entry_icon(entry, is_oldest:), class: "w-4 h-4" %>
<% end %>
<div class="text-sm">
<%= tag.p valuation.date, class: "text-gray-900 font-medium" %>
<%= tag.p valuation.oldest? ? t(".start_balance") : t(".value_update"), class: "text-gray-500" %>
<%= tag.p entry.date, class: "text-gray-900 font-medium" %>
<%= tag.p is_oldest ? t(".start_balance") : t(".value_update"), class: "text-gray-500" %>
</div>
</div>
<div class="col-span-2 justify-self-end">
<%= tag.p format_money(valuation.value_money), class: "font-medium text-sm text-gray-900" %>
<%= tag.p format_money(entry.amount_money), class: "font-medium text-sm text-gray-900" %>
</div>
<div class="col-span-2 justify-self-end font-medium text-sm" style="color: <%= valuation.trend.color %>">
<% if valuation.trend.direction.flat? %>
<div class="col-span-2 justify-self-end font-medium text-sm" style="color: <%= entry.trend.color %>">
<% if entry.trend.direction.flat? %>
<%= tag.span t(".no_change"), class: "text-gray-500" %>
<% else %>
<%= tag.span format_money(valuation.trend.value) %>
<%= tag.span "(#{valuation.trend.percent}%)" %>
<%= tag.span format_money(entry.trend.value) %>
<%= tag.span "(#{entry.trend.percent}%)" %>
<% end %>
</div>
<div class="col-span-1 justify-self-end">
<%= contextual_menu do %>
<div class="w-48 p-1 text-sm leading-6 text-gray-900 bg-white shadow-lg shrink rounded-xl ring-1 ring-gray-900/5">
<%= contextual_menu_modal_action_item t(".edit_entry"), edit_account_valuation_path(valuation.account, valuation) %>
<%= contextual_menu_modal_action_item t(".edit_entry"), edit_account_entry_path(account, entry) %>
<%= contextual_menu_destructive_item t(".delete_entry"),
account_valuation_path(valuation.account, valuation),
account_entry_path(account, entry),
turbo_frame: "_top",
turbo_confirm: {
title: t(".confirm_title"),

View file

@ -0,0 +1,3 @@
<%= turbo_frame_tag dom_id(@entry) do %>
<%= render permitted_entryable_partial_path(@entry, "new"), entry: @entry %>
<% end %>

View file

@ -0,0 +1 @@
<%= render partial: permitted_entryable_partial_path(@entry, "show"), locals: { entry: @entry } %>

View file

@ -12,15 +12,15 @@
<div id="transactions" data-controller="bulk-select" data-bulk-select-resource-value="<%= t(".transaction") %>">
<div hidden id="transaction-selection-bar" data-bulk-select-target="selectionBar">
<%= render "account/transactions/selection_bar" %>
<%= render "selection_bar" %>
</div>
<% if @transactions.empty? %>
<% if @transaction_entries.empty? %>
<p class="text-gray-500 py-4"><%= t(".no_transactions") %></p>
<% else %>
<div class="space-y-6">
<% group_transactions_by_date(@transactions).each do |date, group| %>
<%= render "transaction_group", date:, transactions: group[:transactions], transfers: group[:transfers] %>
<% @transaction_entries.group_by(&:date).each do |date, entries| %>
<%= render "entry_group", date:, entries: entries %>
<% end %>
</div>
<% end %>

View file

@ -2,8 +2,8 @@
<div class="bg-white space-y-4 p-5 border border-alpha-black-25 rounded-xl shadow-xs">
<div class="flex items-center justify-between">
<%= tag.h2 t(".valuations"), class: "font-medium text-lg" %>
<%= link_to new_account_valuation_path(@account),
data: { turbo_frame: dom_id(Account::Valuation.new) },
<%= link_to new_account_entry_path(@account, entryable_type: "Account::Valuation"),
data: { turbo_frame: dom_id(@account.entries.account_valuations.new) },
class: "flex gap-1 font-medium items-center bg-gray-50 text-gray-900 p-2 rounded-lg" do %>
<%= lucide_icon("plus", class: "w-5 h-5 text-gray-900") %>
<%= tag.span t(".new_entry"), class: "text-sm" %>
@ -19,13 +19,13 @@
</div>
<div class="rounded-lg bg-white border-alpha-black-25 shadow-xs">
<%= turbo_frame_tag dom_id(Account::Valuation.new) %>
<%= turbo_frame_tag dom_id(@account.entries.account_valuations.new) %>
<% valuations = @account.valuations.reverse_chronological %>
<% if valuations.any? %>
<%= render partial: "valuation",
collection: @account.valuations.reverse_chronological,
spacer_template: "valuation_ruler" %>
<% if @valuation_entries.any? %>
<%= render partial: "account/entries/entryables/valuation/valuation",
collection: @valuation_entries,
as: :entry,
spacer_template: "ruler" %>
<% else %>
<p class="text-gray-500 text-sm p-4"><%= t(".no_valuations") %></p>
<% end %>

View file

@ -1 +0,0 @@
<%= render "account/transactions/transaction", transaction: @transaction %>

View file

@ -1,21 +0,0 @@
<%# locals: (date:, transactions:, transfers: [], selectable: true, **transaction_opts) %>
<div id="date-group-<%= date %>" class="bg-gray-25 rounded-xl p-1 w-full" data-bulk-select-target="group">
<div class="py-2 px-4 flex items-center justify-between font-medium text-xs text-gray-500">
<div class="flex pl-0.5 items-center gap-4">
<% if selectable %>
<%= check_box_tag "#{date}_transactions_selection",
class: ["maybe-checkbox maybe-checkbox--light", "hidden": transactions.count == 0],
id: "selection_transaction_#{date}",
data: { action: "bulk-select#toggleGroupSelection" } %>
<% end %>
<%= tag.span "#{date.strftime('%b %d, %Y')} · #{transactions.size + (transfers.size * 2)}" %>
</div>
<%= totals_by_currency(collection: transactions, money_method: :amount_money, negate: true) %>
</div>
<div class="bg-white shadow-xs rounded-md border border-alpha-black-25 divide-y divide-alpha-black-50">
<%= render transactions, selectable:, **transaction_opts.except(:selectable) %>
<%= render transfers %>
</div>
</div>

View file

@ -1,103 +0,0 @@
<%= drawer do %>
<div>
<header class="mb-4 space-y-1">
<div class="flex items-center gap-4">
<h3 class="font-medium">
<span class="text-2xl"><%= format_money -@transaction.amount_money %></span>
<span class="text-lg text-gray-500"><%= @transaction.currency %></span>
</h3>
<% if @transaction.marked_as_transfer %>
<%= lucide_icon "arrow-left-right", class: "text-gray-500 mt-1 w-5 h-5" %>
<% end %>
</div>
<span class="text-sm text-gray-500"><%= @transaction.date.strftime("%A %d %B") %></span>
</header>
<div class="space-y-2">
<details class="group space-y-2" open>
<summary class="flex list-none items-center justify-between rounded-xl px-3 py-2 text-xs font-medium uppercase text-gray-500 bg-gray-25 focus-visible:outline-none">
<h4><%= t(".overview") %></h4>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<div class="pb-6">
<%= form_with model: [@account, @transaction], url: account_transaction_path, html: { data: { controller: "auto-submit-form" } } do |f| %>
<div class="space-y-2">
<%= f.text_field :name, label: t(".name_label"), "data-auto-submit-form-target": "auto" %>
<%= f.date_field :date, label: t(".date_label"), max: Date.today, "data-auto-submit-form-target": "auto" %>
<% unless @transaction.marked_as_transfer %>
<%= f.collection_select :category_id, Current.family.categories.alphabetically, :id, :name, { prompt: t(".category_placeholder"), label: t(".category_label"), class: "text-gray-400" }, "data-auto-submit-form-target": "auto" %>
<%= f.collection_select :merchant_id, Current.family.merchants.alphabetically, :id, :name, { prompt: t(".merchant_placeholder"), label: t(".merchant_label"), class: "text-gray-400" }, "data-auto-submit-form-target": "auto" %>
<% end %>
<%= f.collection_select :account_id, Current.family.accounts.alphabetically, :id, :name, { prompt: t(".account_placeholder"), label: t(".account_label"), class: "text-gray-500" }, { class: "form-field__input cursor-not-allowed text-gray-400", disabled: "disabled" } %>
</div>
<% end %>
</div>
</details>
<details class="group space-y-2" open>
<summary class="flex list-none items-center justify-between rounded-xl px-3 py-2 text-xs font-medium uppercase text-gray-500 bg-gray-25 focus-visible:outline-none">
<h4><%= t(".additional") %></h4>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<div class="pb-6 space-y-2">
<%= form_with model: [@account, @transaction], url: account_transaction_path, html: { data: { controller: "auto-submit-form" } } do |f| %>
<%= f.select :tag_ids,
options_for_select(Current.family.tags.alphabetically.pluck(:name, :id), @transaction.tag_ids),
{
multiple: true,
label: t(".tags_label"),
class: "placeholder:text-gray-500"
},
"data-auto-submit-form-target": "auto" %>
<%= f.text_area :notes, label: t(".note_label"), placeholder: t(".note_placeholder"), "data-auto-submit-form-target": "auto" %>
<% end %>
</div>
</details>
<details class="group space-y-2" open>
<summary class="flex list-none items-center justify-between rounded-xl px-3 py-2 text-xs font-medium uppercase text-gray-500 bg-gray-25 focus-visible:outline-none">
<h4><%= t(".settings") %></h4>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<div class="pb-6">
<%= form_with model: [@account, @transaction], url: account_transaction_path, html: { class: "p-3 space-y-3", data: { controller: "auto-submit-form" } } do |f| %>
<div class="flex cursor-pointer items-center gap-2 justify-between">
<div class="text-sm space-y-1">
<h4 class="text-gray-900"><%= t(".exclude_title") %></h4>
<p class="text-gray-500"><%= t(".exclude_subtitle") %></p>
</div>
<div class="relative inline-block select-none">
<%= f.check_box :excluded, class: "sr-only peer", "data-auto-submit-form-target": "auto" %>
<label for="account_transaction_excluded" class="maybe-switch"></label>
</div>
</div>
<% end %>
<% unless @transaction.transfer? %>
<div class="flex items-center justify-between gap-2 p-3">
<div class="text-sm space-y-1">
<h4 class="text-gray-900"><%= t(".delete_title") %></h4>
<p class="text-gray-500"><%= t(".delete_subtitle") %></p>
</div>
<%= button_to t(".delete"),
account_transaction_path(@account, @transaction),
method: :delete,
class: "rounded-lg px-3 py-2 text-red-500 text-sm font-medium border border-alpha-black-200",
data: { turbo_confirm: true, turbo_frame: "_top" } %>
</div>
<% end %>
</div>
</details>
</div>
</div>
<% end %>

View file

@ -19,11 +19,11 @@
</section>
<section class="space-y-2">
<%= f.text_field :name, value: transfer.transactions.first&.name, label: t(".description"), placeholder: t(".description_placeholder"), required: true %>
<%= f.text_field :name, value: transfer.name, label: t(".description"), placeholder: t(".description_placeholder"), required: true %>
<%= f.collection_select :from_account_id, Current.family.accounts.alphabetically, :id, :name, { prompt: t(".select_account"), label: t(".from") }, required: true %>
<%= f.collection_select :to_account_id, Current.family.accounts.alphabetically, :id, :name, { prompt: t(".select_account"), label: t(".to") }, required: true %>
<%= f.money_field :amount_money, label: t(".amount"), required: true %>
<%= f.date_field :date, value: transfer.transactions.first&.date, label: t(".date"), required: true, max: Date.current %>
<%= f.date_field :date, value: transfer.date, label: t(".date"), required: true, max: Date.current %>
</section>
<section>

View file

@ -1,34 +1,49 @@
<%= turbo_frame_tag dom_id(transfer), class: "block" do %>
<details class="group flex items-center text-gray-900 text-sm font-medium">
<summary class="flex items-center justify-between p-4">
<div class="flex items-center gap-4">
<%= button_to account_transfer_path(transfer),
method: :delete,
class: "flex items-center group/transfer",
data: {
turbo_frame: "_top",
turbo_confirm: {
title: t(".remove_title"),
body: t(".remove_body"),
confirm: t(".remove_confirm")
}
} do %>
<%= lucide_icon "arrow-left-right", class: "group-hover/transfer:hidden w-5 h-5 text-gray-500" %>
<%= lucide_icon "unlink", class: "group-hover/transfer:inline-block hidden w-5 h-5 text-gray-500" %>
<% end %>
<%# locals: (transfer:, selectable: true, editable: true, short: false, **opts) %>
<div class="max-w-full pr-10 select-none">
<%= tag.p t(".transfer_name", from_account: transfer.outflow_transaction&.account&.name, to_account: transfer.inflow_transaction&.account&.name) %>
<%= turbo_frame_tag dom_id(transfer) do %>
<div class="grid grid-cols-12 items-center text-gray-900 text-sm font-medium p-4">
<div class="col-span-7 flex items-center">
<% if selectable %>
<%= check_box_tag dom_id(transfer, "selection"),
disabled: true,
class: "mr-3 cursor-not-allowed maybe-checkbox maybe-checkbox--light" %>
<% end %>
<%= tag.div class: short ? "max-w-[250px]" : "max-w-[325px]" do %>
<div class="flex items-center gap-2">
<%= circle_logo("T") %>
<%= tag.p transfer.name, class: "truncate text-gray-900" %>
</div>
</div>
<% end %>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<%= button_to account_transfer_path(transfer),
method: :delete,
class: "ml-2 flex items-center group/transfer hover:bg-gray-50 rounded-md p-1",
data: {
turbo_frame: "_top",
turbo_confirm: {
title: t(".remove_title"),
body: t(".remove_body"),
confirm: t(".remove_confirm")
}
} do %>
<div class="divide-y divide-alpha-black-200">
<% transfer.transactions.each do |transaction| %>
<%= render transaction, selectable: false, editable: false %>
<%= lucide_icon "link-2", class: "group-hover/transfer:hidden w-4 h-4 text-gray-500" %>
<%= lucide_icon "unlink", class: "group-hover/transfer:inline-block hidden w-4 h-4 text-gray-500" %>
<% end %>
</div>
</details>
<% unless short %>
<div class="col-span-3 flex items-center gap-2">
<%= circle_logo(transfer.from_name[0].upcase, size: "sm") %>
<span class="text-gray-500 font-medium">&rarr;</span>
<%= circle_logo(transfer.to_name[0].upcase, size: "sm") %>
</div>
<% end %>
<div class="ml-auto <%= short ? "col-span-5" : "col-span-2" %>">
<%= tag.p format_money(transfer.amount_money), class: "font-medium" %>
</div>
</div>
<% end %>

View file

@ -1,23 +0,0 @@
<%# locals: (valuation:) %>
<%= form_with model: valuation,
data: { turbo_frame: "_top" },
url: valuation.new_record? ? account_valuations_path(valuation.account) : account_valuation_path(valuation.account, valuation),
builder: ActionView::Helpers::FormBuilder do |f| %>
<div class="grid grid-cols-10 p-4 items-center">
<div class="col-span-7 flex items-center gap-4">
<div class="w-8 h-8 rounded-full p-1.5 flex items-center justify-center bg-gray-500/5">
<%= lucide_icon("pencil-line", class: "w-4 h-4 text-gray-500") %>
</div>
<div class="w-full flex items-center justify-between gap-2">
<%= f.date_field :date, required: "required", max: Date.today, class: "border border-alpha-black-200 bg-white rounded-lg shadow-xs min-w-[200px] px-3 py-1.5 text-gray-900 text-sm" %>
<%= f.number_field :value, required: "required", placeholder: "0.00", step: "0.01", class: "bg-white border border-alpha-black-200 rounded-lg shadow-xs text-gray-900 text-sm px-3 py-1.5 text-right" %>
<%= f.hidden_field :currency, value: valuation.account.currency %>
</div>
</div>
<div class="col-span-3 flex gap-2 justify-end items-center">
<%= link_to t(".cancel"), account_valuations_path(valuation.account), class: "text-sm text-gray-900 hover:text-gray-800 font-medium px-3 py-1.5" %>
<%= f.submit class: "bg-gray-50 rounded-lg font-medium px-3 py-1.5 cursor-pointer hover:bg-gray-100 text-sm" %>
</div>
</div>
<% end %>

View file

@ -1,5 +0,0 @@
<div class="bg-white space-y-4 p-5 border border-alpha-black-25 rounded-xl shadow-xs">
<div class="p-5 flex justify-center items-center">
<%= tag.p t(".loading"), class: "text-gray-500 animate-pulse text-sm" %>
</div>
</div>

View file

@ -1,3 +0,0 @@
<%= turbo_frame_tag dom_id(@valuation) do %>
<%= render "form", valuation: @valuation %>
<% end %>

View file

@ -1,4 +0,0 @@
<%= turbo_frame_tag dom_id(@valuation) do %>
<%= render "form", valuation: @valuation %>
<div class="h-px bg-alpha-black-50 ml-20 mr-4"></div>
<% end %>

View file

@ -1 +0,0 @@
<%= render "valuation", valuation: @valuation %>

View file

@ -81,12 +81,12 @@
<div class="min-h-[800px]">
<% if selected_tab == "transactions" %>
<%= turbo_frame_tag dom_id(@account, "transactions"), src: account_transactions_path(@account) do %>
<%= render "account/transactions/loading" %>
<%= turbo_frame_tag dom_id(@account, "transactions"), src: transaction_account_entries_path(@account) do %>
<%= render "account/entries/loading" %>
<% end %>
<% else %>
<%= turbo_frame_tag dom_id(@account, "valuations"), src: account_valuations_path(@account) do %>
<%= render "account/valuations/loading" %>
<%= turbo_frame_tag dom_id(@account, "valuations"), src: valuation_account_entries_path(@account) do %>
<%= render "account/entries/loading" %>
<% end %>
<% end %>
</div>

View file

@ -2,7 +2,7 @@
<% is_selected = category.id === @selected_category&.id %>
<%= content_tag :div, class: ["filterable-item flex justify-between items-center border-none rounded-lg px-2 py-1 group w-full", { "bg-gray-25": is_selected }], data: { filter_name: category.name } do %>
<%= button_to account_transaction_row_path(@transaction.account, @transaction, transaction: { category_id: category.id }), method: :patch, data: { turbo_frame: dom_id(@transaction) }, class: "flex w-full items-center gap-1.5 cursor-pointer" do %>
<%= button_to account_entry_path(@transaction.entry.account, @transaction.entry, account_entry: { entryable_type: "Account::Transaction", entryable_attributes: { id: @transaction.id, category_id: category.id } }), method: :patch, data: { turbo_frame: dom_id(@transaction.entry) }, class: "flex w-full items-center gap-1.5 cursor-pointer" do %>
<span class="w-5 h-5">
<%= lucide_icon("check", class: "w-5 h-5 text-gray-500") if is_selected %>
</span>

View file

@ -25,10 +25,10 @@
<% end %>
<% if @transaction.category %>
<%= button_to account_transaction_row_path(@transaction.account, @transaction),
<%= button_to account_entry_path(@transaction.entry.account, @transaction.entry),
method: :patch,
data: { turbo_frame: dom_id(@transaction) },
params: { transaction: { category_id: nil } },
data: { turbo_frame: dom_id(@transaction.entry) },
params: { account_entry: { entryable_type: "Account::Transaction", entryable_attributes: { id: @transaction.id, category_id: nil } } },
class: "flex text-sm font-medium items-center gap-2 text-gray-500 w-full rounded-lg p-2 hover:bg-gray-100" do %>
<%= lucide_icon "minus", class: "w-5 h-5" %>

View file

@ -9,12 +9,11 @@
</div>
<div class="mb-8 space-y-4">
<% transactions = @import.dry_run %>
<% group_transactions_by_date(transactions).each do |date, group| %>
<%= render "account/transactions/transaction_group",
<% transaction_entries = @import.dry_run %>
<% transaction_entries.group_by(&:date).each do |date, transactions| %>
<%= render "account/entries/entry_group",
date: date,
transactions: group[:transactions],
transfers: group[:transfers],
entries: transaction_entries,
show_tags: true,
selectable: false,
editable: false %>

View file

@ -25,7 +25,7 @@
<% end %>
</div>
<div class="flex justify-between gap-4">
<%= previous_setting("Rules", account_transaction_rules_path) %>
<%= previous_setting("Rules", rules_transactions_path) %>
<%= next_setting("What's new", changelog_path) %>
</div>
</div>

View file

@ -35,6 +35,6 @@
</div>
<div class="flex justify-between gap-4">
<%= previous_setting("Categories", categories_path) %>
<%= next_setting("Rules", account_transaction_rules_path) %>
<%= next_setting("Rules", rules_transactions_path) %>
</div>
</div>

View file

@ -156,17 +156,16 @@
<section class="grid grid-cols-2 gap-4 items-baseline">
<div class="bg-white p-4 border border-alpha-black-25 shadow-xs rounded-xl space-y-4">
<h2 class="text-lg font-medium text-gray-900"><%= t(".transactions") %></h2>
<% if @transactions.empty? %>
<% if @transaction_entries.empty? %>
<div class="text-gray-500 flex items-center justify-center py-12">
<p><%= t(".no_transactions") %></p>
</div>
<% else %>
<div class="text-gray-500 p-1 space-y-1 bg-gray-25 rounded-xl">
<% group_transactions_by_date(@transactions).each do |date, group| %>
<%= render "account/transactions/transaction_group",
<% @transaction_entries.group_by(&:date).each do |date, transactions| %>
<%= render "account/entries/entry_group",
date: date,
transactions: group[:transactions],
transfers: group[:transfers],
entries: transactions,
selectable: false,
editable: false,
short: true %>

View file

@ -56,7 +56,7 @@
<%= sidebar_link_to t(".merchants_label"), merchants_path, icon: "store" %>
</li>
<li>
<%= sidebar_link_to t(".rules_label"), account_transaction_rules_path, icon: "list-checks" %>
<%= sidebar_link_to t(".rules_label"), rules_transactions_path, icon: "list-checks" %>
</li>
<li>
<%= sidebar_link_to t(".imports_label"), imports_path, icon: "download" %>

View file

@ -0,0 +1,13 @@
<%# locals: (name:, hex: nil, size: "md") %>
<% size_classes = {
"sm" => "w-6 h-6",
"md" => "w-8 h-8",
"lg" => "w-10 h-10",
"full" => "w-full h-full"
} %>
<%= tag.div style: mixed_hex_styles(hex),
class: [size_classes[size], "flex shrink-0 items-center justify-center rounded-full"] do %>
<%= tag.span name[0].upcase, class: ["font-medium", size == "sm" ? "text-xs" : "text-sm"] %>
<% end %>

View file

@ -1,4 +1,4 @@
<%= form_with model: @transaction, url: transactions_path, scope: "transaction", data: { turbo_frame: "_top" } do |f| %>
<%= form_with model: @entry, url: transactions_path, data: { turbo_frame: "_top" } do |f| %>
<section>
<fieldset class="bg-gray-50 rounded-lg p-1 grid grid-flow-col justify-stretch gap-x-2">
<%= radio_tab_tag form: f, name: :nature, value: :expense, label: t(".expense"), icon: "minus-circle", checked: params[:nature] == "expense" || params[:nature].nil? %>
@ -14,7 +14,10 @@
<%= f.text_field :name, label: t(".description"), placeholder: t(".description_placeholder"), required: true %>
<%= f.collection_select :account_id, Current.family.accounts.alphabetically, :id, :name, { prompt: t(".account_prompt"), label: t(".account") }, required: true %>
<%= f.money_field :amount_money, label: t(".amount"), required: true %>
<%= f.collection_select :category_id, Current.family.categories.alphabetically, :id, :name, { prompt: t(".category_prompt"), label: t(".category") } %>
<%= f.hidden_field :entryable_type, value: "Account::Transaction" %>
<%= f.fields_for :entryable do |ef| %>
<%= ef.collection_select :category_id, Current.family.categories.alphabetically, :id, :name, { prompt: t(".category_prompt"), label: t(".category") } %>
<% end %>
<%= f.date_field :date, label: t(".date"), required: true, max: Date.today %>
</section>

View file

@ -1,39 +1,39 @@
<%# locals: (pagy:) %>
<nav class="flex items-center justify-between px-4 mt-4 sm:px-0 w-full">
<div class="flex">
<nav class="flex w-full items-center justify-between">
<div class="flex items-center gap-1">
<div>
<% if pagy.prev %>
<%= link_to pagy_url_for(pagy, pagy.prev), class: "inline-flex items-center px-3 py-3 text-sm font-medium text-gray-500 hover:border-gray-300 hover:text-gray-700" do %>
<%= link_to pagy_url_for(pagy, pagy.prev), class: "inline-flex items-center p-2 text-sm font-medium text-gray-500 hover:border-gray-300 hover:text-gray-700" do %>
<%= lucide_icon("chevron-left", class: "w-5 h-5 text-gray-500") %>
<% end %>
<% else %>
<div class="inline-flex items-center px-3 py-3 text-sm font-medium hover:border-gray-300">
<div class="inline-flex items-center p-2 text-sm font-medium hover:border-gray-300">
<%= lucide_icon("chevron-left", class: "w-5 h-5 text-gray-200") %>
</div>
<% end %>
</div>
<div class="bg-gray-25 rounded-xl">
<div class="rounded-xl p-1 bg-gray-25">
<% pagy.series.each do |series_item| %>
<% if series_item.is_a?(Integer) %>
<%= link_to pagy_url_for(pagy, series_item), class: "inline-flex items-center px-3 py-3 text-sm font-medium text-gray-500 hover:border-gray-300 hover:text-gray-700" do %>
<%= link_to pagy_url_for(pagy, series_item), class: "rounded-md px-2 py-1 inline-flex items-center text-sm font-medium text-gray-500 hover:border-gray-300 hover:text-gray-700" do %>
<%= series_item %>
<% end %>
<% elsif series_item.is_a?(String) %>
<%= link_to pagy_url_for(pagy, series_item), class: "shadow-lg ring-2 ring-inset ring-gray-200 rounded-xl bg-white inline-flex items-center m-1 px-4 py-2 text-sm font-medium text-gray-900" do %>
<%= link_to pagy_url_for(pagy, series_item), class: "rounded-md px-2 py-1 bg-white border border-alpha-black-25 shadow-xs inline-flex items-center text-sm font-medium text-gray-900" do %>
<%= series_item %>
<% end %>
<% elsif series_item == :gap %>
<span class="inline-flex items-center px-3 py-3 text-sm font-medium text-gray-500">...</span>
<span class="inline-flex items-center px-2 py-1 text-sm font-medium text-gray-500">...</span>
<% end %>
<% end %>
</div>
<div>
<% if pagy.next %>
<%= link_to pagy_url_for(pagy, pagy.next), class: "inline-flex items-center px-3 py-3 text-sm font-medium text-gray-500 hover:border-gray-300 hover:text-gray-700" do %>
<%= link_to pagy_url_for(pagy, pagy.next), class: "inline-flex items-center p-2 text-sm font-medium text-gray-500 hover:border-gray-300 hover:text-gray-700" do %>
<%= lucide_icon("chevron-right", class: "w-5 h-5 text-gray-500") %>
<% end %>
<% else %>
<div class="inline-flex items-center px-3 py-3 text-sm font-medium hover:border-gray-300">
<div class="inline-flex items-center p-2 text-sm font-medium hover:border-gray-300">
<%= lucide_icon("chevron-right", class: "w-5 h-5 text-gray-200") %>
</div>
<% end %>
@ -47,7 +47,7 @@
data: { controller: "auto-submit-form" } do |f| %>
<%= f.label :per_page, t(".rows_per_page"), class: "text-sm text-gray-500" %>
<%= f.select :per_page,
options_for_select(["10", "20", "30", "50"], params[:per_page]),
options_for_select(["10", "20", "30", "50"], pagy.items),
{},
class: "py-1.5 pr-8 text-sm text-gray-900 font-medium border border-gray-200 rounded-lg focus:border-gray-900 focus:ring-gray-900 focus-visible:ring-gray-900",
data: { "auto-submit-form-target": "auto" } %>

View file

@ -28,44 +28,26 @@
<div class="pb-6 space-y-2">
<%= form.date_field :date, label: t(".date_label"), max: Date.current %>
</div>
</details>
<details class="group space-y-2" open>
<summary class="flex list-none items-center justify-between rounded-xl px-3 py-2 text-xs font-medium uppercase text-gray-500 bg-gray-25 focus-visible:outline-none">
<h4><%= t(".details") %></h4>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<div class="space-y-2">
<%= form.collection_select :category_id, Current.family.categories.alphabetically, :id, :name, { prompt: t(".category_placeholder"), label: t(".category_label"), class: "text-gray-400" } %>
<%= form.collection_select :merchant_id, Current.family.merchants.alphabetically, :id, :name, { prompt: t(".merchant_placeholder"), label: t(".merchant_label"), class: "text-gray-400" } %>
</div>
</details>
<details class="group space-y-2" open>
<summary class="flex list-none items-center justify-between rounded-xl px-3 py-2 text-xs font-medium uppercase text-gray-500 bg-gray-25 focus-visible:outline-none">
<h4><%= t(".additional") %></h4>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<div>
<%= form.text_area :notes, label: t(".note_label"), placeholder: t(".note_placeholder"), rows: 5 %>
</div>
</details>
<details class="group space-y-2" open>
<summary class="flex list-none items-center justify-between rounded-xl px-3 py-2 text-xs font-medium uppercase text-gray-500 bg-gray-25 focus-visible:outline-none">
<h4><%= t(".settings") %></h4>
<%= lucide_icon "chevron-down", class: "group-open:transform group-open:rotate-180 text-gray-500 w-5" %>
</summary>
<div class="flex cursor-pointer items-center justify-between gap-4 p-3 pb-6">
<div class="text-sm space-y-1">
<h4 class="text-gray-900"><%= t(".exclude_title") %></h4>
<p class="text-gray-500"><%= t(".exclude_subtitle") %></p>
</div>
<div class="relative inline-block select-none">
<%= form.check_box :excluded, class: "sr-only peer" %>
<label for="bulk_update_excluded" class="maybe-switch"></label>
</div>
</div>
</details>
</div>
</div>
</div>
</div>
<div class="flex justify-end items-center gap-2">
<%= link_to t(".cancel"), transactions_path, class: "text-sm font-medium text-gray-900 px-3 py-2" %>

View file

@ -3,19 +3,20 @@
<%= render "summary", totals: @totals %>
<div id="transactions" data-controller="bulk-select" data-bulk-select-resource-value="<%= t(".transaction") %>" class="overflow-y-auto flex flex-col bg-white rounded-xl border border-alpha-black-25 shadow-xs pb-4">
<div class="p-4 pb-0">
<%= render partial: "transactions/searches/search", locals: { transactions: @transactions } %>
</div>
<div id="transactions"
data-controller="bulk-select"
data-bulk-select-resource-value="<%= t(".transaction") %>"
class="overflow-y-auto flex flex-col bg-white rounded-xl border border-alpha-black-25 shadow-xs p-4">
<%= render "transactions/searches/search" %>
<% if @transactions.present? %>
<div hidden id="transaction-selection-bar" data-bulk-select-target="selectionBar">
<%= render "account/transactions/selection_bar" %>
<% if @transaction_entries.present? %>
<div hidden id="entry-selection-bar" data-bulk-select-target="selectionBar">
<%= render "account/entries/selection_bar" %>
</div>
<div class="grow overflow-y-auto px-4">
<div class="grow overflow-y-auto">
<div class="grid grid-cols-12 bg-gray-25 rounded-xl px-5 py-3 text-xs uppercase font-medium text-gray-500 items-center mb-4">
<div class="pl-0.5 col-span-4 flex items-center gap-4">
<%= check_box_tag "selection_transaction",
<%= check_box_tag "selection_entry",
class: "maybe-checkbox maybe-checkbox--light",
data: { action: "bulk-select#togglePageSelection" } %>
<p class="col-span-4">transaction</p>
@ -26,19 +27,17 @@
<p class="col-span-2 justify-self-end">amount</p>
</div>
<div class="space-y-6">
<% group_transactions_by_date(@transactions).each do |date, group| %>
<%= render "account/transactions/transaction_group", date:, transactions: group[:transactions], transfers: group[:transfers] %>
<% @transaction_entries.group_by(&:date).each do |date, entries| %>
<%= render "account/entries/entry_group", date:, entries: %>
<% end %>
</div>
</div>
<% else %>
<%= render "account/transactions/empty" %>
<%= render "account/entries/empty" %>
<% end %>
<div class="px-4">
<% if @pagy.pages > 1 %>
<%= render "pagination", pagy: @pagy %>
<% end %>
<div class="pt-4">
<%= render "pagination", pagy: @pagy %>
</div>
</div>
</div>

View file

@ -5,6 +5,6 @@
<%= lucide_icon "x", class: "w-5 h-5 text-gray-500", data: { action: "click->modal#close" } %>
</header>
<%= render "form", transaction: @transaction %>
<%= render "form", transaction: @transaction, entry: @entry %>
</article>
<% end %>

View file

@ -1,4 +1,3 @@
<%# locals: (transactions:) %>
<%= form_with url: transactions_path,
id: "transactions-search",
scope: :q,

View file

@ -1,13 +1,13 @@
<%= render partial: "transactions/searches/form", locals: { transactions: transactions } %>
<%= render "transactions/searches/form" %>
<ul id="transaction-search-filters" class="flex items-center flex-wrap gap-2">
<% @q.each do |param_key, param_value| %>
<% unless param_value.blank? %>
<div class="pb-4">
<% Array(param_value).each do |value| %>
<%= render partial: "transactions/searches/filters/badge", locals: { param_key: param_key, param_value: value } %>
<% end %>
</div>
<div class="pb-4">
<% Array(param_value).each do |value| %>
<%= render partial: "transactions/searches/filters/badge", locals: { param_key: param_key, param_value: value } %>
<% end %>
</div>
<% end %>
<% end %>
</ul>