Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add split_transaction rule action (#3020)

GFRbf8d6cc39a10
diff --git a/app/components/DS/merchant_select.html.erb b/app/components/DS/merchant_select.html.erb
index e85c154789..7a6c2b4ca0 100644
--- a/app/components/DS/merchant_select.html.erb
+++ b/app/components/DS/merchant_select.html.erb
@@ -15,6 +15,7 @@
class="form-field__input w-full flex items-center gap-2 <%= "cursor-not-allowed text-subdued" if disabled %>"
data-merchant-select-target="button"
data-action="click->merchant-select#toggle"
+ id="<%= form.field_id(method) %>"
aria-haspopup="listbox"
aria-expanded="false"
aria-controls="<%= menu_id %>"
diff --git a/app/components/DS/select.html.erb b/app/components/DS/select.html.erb
index 3bd6600af6..547eb4b528 100644
--- a/app/components/DS/select.html.erb
+++ b/app/components/DS/select.html.erb
@@ -3,7 +3,7 @@
<div class="relative" data-controller="select <%= "list-filter" if searchable %> form-dropdown" data-select-menu-placement-value="<%= menu_placement %>" data-action="dropdown:select->form-dropdown#onSelect">
<div class="form-field <%= options[:container_class] %>">
<div class="form-field__body">
- <%= form.label method, options[:label], class: "form-field__label", id: "#{method}_label" if options[:label].present? %>
+ <%= form.label method, options[:label], class: "form-field__label", id: label_id if options[:label].present? %>
<%= form.hidden_field method,
value: @selected_value,
data: {
@@ -20,14 +20,14 @@
value>" — referencing only the label would override the
button's text node and suppress the current value. %>
<button type="button"
- id="<%= method %>_trigger"
+ id="<%= trigger_id %>"
class="form-field__input w-full"
data-select-target="button"
data-action="click->select#toggle focus->select#handleButtonFocus"
aria-haspopup="listbox"
aria-expanded="false"
tabindex="0"
- <%= "aria-labelledby=\"#{method}_label #{method}_trigger\"".html_safe if options[:label].present? %>>
+ <%= tag.attributes(aria: { labelledby: "#{label_id} #{trigger_id}" }) if options[:label].present? %>>
<%= selected_item&.dig(:label) || @placeholder %>
</button>
</div>
diff --git a/app/components/DS/select.rb b/app/components/DS/select.rb
index a9a9342198..3c0ca1ab57 100644
--- a/app/components/DS/select.rb
+++ b/app/components/DS/select.rb
@@ -8,13 +8,14 @@ module DS
RGB_COLOR_REGEX = /\Argb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)\z/
DEFAULT_COLOR = "#737373"
- def initialize(form:, method:, items:, selected: nil, placeholder: I18n.t("helpers.select.default_label"), variant: :simple, include_blank: nil, searchable: false, menu_placement: :auto, **options)
+ def initialize(form:, method:, items:, selected: nil, placeholder: I18n.t("helpers.select.default_label"), variant: :simple, include_blank: nil, searchable: false, menu_placement: :auto, scoped_ids: false, **options)
@form = form
@method = method
@placeholder = placeholder
@variant = variant
@searchable = searchable
@menu_placement = normalize_menu_placement(menu_placement)
+ @scoped_ids = scoped_ids
@options = options
normalized_items = normalize_items(items)
@@ -31,6 +32,17 @@ module DS
@selected_value = selected
end
+ # Ids are "<method>_label"/"<method>_trigger" by default. Repeated rows (e.g. split rows) pass
+ # scoped_ids so each row gets its own ids from the form scope and aria-labelledby resolves to
+ # that row's label rather than the first one in the document.
+ def label_id
+ @scoped_ids ? form.field_id(method, :label) : "#{method}_label"
+ end
+
+ def trigger_id
+ @scoped_ids ? form.field_id(method, :trigger) : "#{method}_trigger"
+ end
+
def selected_item
items.find { |item| item[:value] == selected_value }
end
diff --git a/app/components/DS/tag_select.html.erb b/app/components/DS/tag_select.html.erb
index 0ebaae525c..f1516807c0 100644
--- a/app/components/DS/tag_select.html.erb
+++ b/app/components/DS/tag_select.html.erb
@@ -16,15 +16,16 @@
<% end %>
<button type="button"
- class="form-field__input form-field__input--multiselect-trigger min-h-7 flex items-center gap-2 pr-8 <%= "cursor-not-allowed text-subdued" if disabled %>"
+ class="form-field__input form-field__input--multiselect-trigger <%= trigger_height_class %> flex items-center gap-2 pr-8 <%= "cursor-not-allowed text-subdued" if disabled %>"
data-tag-select-target="button"
data-action="click->tag-select#toggle"
+ id="<%= form.field_id(attribute) %>"
aria-haspopup="listbox"
aria-expanded="false"
aria-controls="<%= menu_id %>"
<% unless show_label %> aria-label="<%= label || helpers.t("transactions.form.tags_label") %>" <% end %>
<%= "disabled" if disabled %>>
- <span class="flex flex-wrap gap-1"
+ <span class="flex flex-wrap gap-1 <%= selection_class %>"
data-tag-select-target="selectionContainer"
data-placeholder="<%= helpers.t("transactions.form.none") %>">
<span class="text-secondary"><%= helpers.t("transactions.form.none") %></span>
diff --git a/app/components/DS/tag_select.rb b/app/components/DS/tag_select.rb
index 537e439711..552aa54d93 100644
--- a/app/components/DS/tag_select.rb
+++ b/app/components/DS/tag_select.rb
@@ -1,11 +1,11 @@
class DS::TagSelect < DesignSystemComponent
attr_reader :form, :tags, :selected_ids, :attribute, :label, :show_label, :disabled,
- :auto_submit, :update_url, :menu_placement, :offset
+ :auto_submit, :update_url, :menu_placement, :offset, :compact
MENU_PLACEMENTS = %w[auto down up].freeze
def initialize(form:, tags:, selected_ids:, attribute: :tag_ids, label: nil, show_label: true,
- disabled: false, auto_submit: false, update_url: nil, menu_placement: :auto, offset: 6)
+ disabled: false, auto_submit: false, update_url: nil, menu_placement: :auto, offset: 6, compact: false)
@form = form
@tags = tags
@selected_ids = selected_ids.map(&:to_s)
@@ -17,12 +17,23 @@ class DS::TagSelect < DesignSystemComponent
@update_url = update_url
@menu_placement = normalize_menu_placement(menu_placement)
@offset = offset
+ @compact = compact
end
def field_name
"#{form.object_name}[#{attribute}][]"
end
+ # Compact keeps the trigger at a plain input's height, so it lines up with the selects next to
+ # it in dense rows (split rows); selected pills overlap the padding instead of growing the field.
+ def trigger_height_class
+ compact ? "min-h-5" : "min-h-7"
+ end
+
+ def selection_class
+ compact ? "-my-0.5" : nil
+ end
+
def menu_id
@menu_id ||= "tag_select_#{field_name.gsub(/\W+/, "_")}_#{object_id}"
end
diff --git a/app/controllers/api/v1/splits_controller.rb b/app/controllers/api/v1/splits_controller.rb
index 49c921b8e2..f3a32d486f 100644
--- a/app/controllers/api/v1/splits_controller.rb
+++ b/app/controllers/api/v1/splits_controller.rb
@@ -10,7 +10,7 @@
class Api::V1::SplitsController < Api::V1::BaseController
include Api::V1::TransactionLookup
- AlreadySplit = Class.new(StandardError)
+ NotSplittable = Class.new(StandardError)
NotSplit = Class.new(StandardError)
# entries.amount is decimal(19,4). Children are rounded independently on
@@ -42,24 +42,19 @@ class Api::V1::SplitsController < Api::V1::BaseController
splits = build_splits
return if performed?
- # Explicit transaction + lock!, NOT Entry#with_lock: on Rails 8.1 the
- # with_lock form silently discards the whole split -- no children, no
- # exception. Verified against real data before relying on this.
- Entry.transaction do
- @entry.lock!
- # Re-check inside the lock: two concurrent POSTs can both clear the
- # check above, and split! validates only its own amounts, so both sets
- # of children would be inserted and the transaction counted twice.
- raise AlreadySplit if @entry.split_parent?
-
- @entry.split!(splits)
- end
+ # Two concurrent POSTs can both clear the check above; split_once! locks
+ # the parent and re-checks, so only one set of children is inserted.
+ raise NotSplittable unless @entry.split_once!(splits)
@entry.sync_account_later
@entry.reload
render_split status: :created
- rescue AlreadySplit
- render_unprocessable("Transaction cannot be split", [ "Transaction is already split" ])
+ rescue NotSplittable
+ # Reload so the reason reflects what the other caller or a sync did in the meantime
+ # (split, excluded, pending, transfer), not the state checked before the lock.
+ @entry.reload
+ @transaction.reload
+ render_unprocessable("Transaction cannot be split", [ not_splittable_reason ])
rescue ActiveRecord::RecordInvalid => e
render_unprocessable(e.message)
end
@@ -75,16 +70,9 @@ class Api::V1::SplitsController < Api::V1::BaseController
splits = build_splits
return if performed?
- Entry.transaction do
- @entry.lock!
- # The split_parent? test above runs before the lock, so a concurrent
- # DELETE can unsplit in between; without this the replacement would
- # resurrect a split the other caller just removed.
- raise NotSplit unless @entry.split_parent?
-
- @entry.unsplit!
- @entry.split!(splits)
- end
+ # The split_parent? test above runs before the lock, so a concurrent DELETE can unsplit in
+ # between; resplit! re-checks under the lock instead of resurrecting the split.
+ raise NotSplit unless @entry.resplit!(splits)
@entry.sync_account_later
@entry.reload
@@ -99,12 +87,7 @@ class Api::V1::SplitsController < Api::V1::BaseController
def destroy
return render_not_split unless @entry.split_parent?
- Entry.transaction do
- @entry.lock!
- raise NotSplit unless @entry.split_parent?
-
- @entry.unsplit!
- end
+ raise NotSplit unless @entry.unsplit_once!
@entry.sync_account_later
head :no_content
@@ -192,10 +175,25 @@ class Api::V1::SplitsController < Api::V1::BaseController
return nil
end
- s = s.permit(:name, :amount, :category_id, :excluded)
- category_id = s[:category_id].presence
- if category_id && !family_category_ids.include?(category_id)
- render_unprocessable("Unknown category: #{category_id}")
+ unless s[:tag_ids].nil? || (s[:tag_ids].is_a?(Array) && s[:tag_ids].all?(String))
+ render_unprocessable("tag_ids must be an array of tag ids")
+ return nil
+ end
+ # permit would silently drop a non-scalar id, storing the child without it.
+ %i[category_id merchant_id].each do |key|
+ next if s[key].nil? || s[key].is_a?(String)
+
+ render_unprocessable("#{key} must be an id")
+ return nil
+ end
+
+ s = s.permit(:name, :amount, :category_id, :merchant_id, :excluded, tag_ids: [])
+ references = { category_id: s[:category_id], merchant_id: s[:merchant_id], tag_ids: s[:tag_ids] }
+
+ unknown = split_references.unknown(**references)
+ if unknown.any?
+ kind, id = unknown.first
+ render_unprocessable("Unknown #{kind}: #{id}")
return nil
end
@@ -213,8 +211,10 @@ class Api::V1::SplitsController < Api::V1::BaseController
# validates presence, so apply the default rather than 422 on it.
name: s[:name].presence || @entry.name,
amount: amount,
- category_id: category_id,
- excluded: s[:excluded]
+ excluded: s[:excluded],
+ # Nothing is dropped here (unknown ids were rejected above); scope only normalizes.
+ # Without a merchant_id the child keeps the parent's merchant (Entry#split!).
+ **split_references.scope(**references)
}
end
rescue ArgumentError, TypeError
@@ -222,10 +222,11 @@ class Api::V1::SplitsController < Api::V1::BaseController
nil
end
- # belongs_to :category is unscoped, so a known UUID from another family
- # would be accepted and then serialized back to the caller.
- def family_category_ids
- @family_category_ids ||= current_resource_owner.family.categories.pluck(:id).to_set
+ # Transaction's belongs_to :category and :merchant are unscoped, so a known UUID from another
+ # family would be accepted and then serialized back to the caller. The same rules as the web
+ # split editor apply: family categories and tags, and any merchant the user can see.
+ def split_references
+ @split_references ||= Entry::SplitReferences.for_user(current_resource_owner.family, current_resource_owner)
end
def not_splittable_reason
diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rb
index 627689dcfe..d51d9e7b32 100644
--- a/app/controllers/rules_controller.rb
+++ b/app/controllers/rules_controller.rb
@@ -231,7 +231,8 @@ class RulesController < ApplicationController
sub_conditions_attributes: [ :id, :condition_type, :operator, :value, :_destroy ]
],
actions_attributes: [
- :id, :action_type, :value, :_destroy, { value: [] }
+ :id, :action_type, :value, :_destroy, { value: [] },
+ split_rows: [ :type, :name, :share, :category_id, :merchant_id, tag_ids: [] ]
]
)
end
diff --git a/app/controllers/splits_controller.rb b/app/controllers/splits_controller.rb
index 1d0e201451..9966c96ea2 100644
--- a/app/controllers/splits_controller.rb
+++ b/app/controllers/splits_controller.rb
@@ -3,7 +3,7 @@ class SplitsController < ApplicationController
before_action :require_split_write_permission!, only: %i[create update destroy]
def new
- @categories = grouped_categories
+ set_form_options
end
def create
@@ -12,14 +12,12 @@ class SplitsController < ApplicationController
return
end
- raw_splits = split_params[:splits]
- raw_splits = raw_splits.values if raw_splits.respond_to?(:values)
-
- splits = raw_splits.map do |s|
- { name: s[:name], amount: s[:amount].to_d * -1, category_id: s[:category_id].presence, excluded: s[:excluded] }
+ # A rule run, an API request or a double submit can split it between the check above and
+ # here; split_once! re-checks under a lock.
+ unless @entry.split_once!(build_splits)
+ redirect_back_or_to transactions_path, alert: t("splits.create.not_splittable")
+ return
end
-
- @entry.split!(splits)
@entry.sync_account_later
redirect_back_or_to transactions_path, notice: t("splits.create.success")
@@ -35,8 +33,8 @@ class SplitsController < ApplicationController
return
end
- @categories = grouped_categories
- @children = @entry.child_entries.includes(:entryable)
+ set_form_options
+ @children = @entry.child_entries.includes(entryable: :tags)
end
def update
@@ -47,16 +45,12 @@ class SplitsController < ApplicationController
return
end
- raw_splits = split_params[:splits]
- raw_splits = raw_splits.values if raw_splits.respond_to?(:values)
+ splits = build_splits
- splits = raw_splits.map do |s|
- { name: s[:name], amount: s[:amount].to_d * -1, category_id: s[:category_id].presence, excluded: s[:excluded] }
- end
-
- Entry.transaction do
- @entry.unsplit!
- @entry.split!(splits)
+ # A concurrent unsplit or edit can land between the check above and here.
+ unless @entry.resplit!(splits)
+ redirect_to transactions_path, alert: t("splits.edit.not_split")
+ return
end
@entry.sync_account_later
@@ -74,7 +68,10 @@ class SplitsController < ApplicationController
return
end
- @entry.unsplit!
+ unless @entry.unsplit_once!
+ redirect_to transactions_path, alert: t("splits.edit.not_split")
+ return
+ end
@entry.sync_account_later
redirect_to transactions_path, notice: t("splits.destroy.success")
@@ -95,7 +92,32 @@ class SplitsController < ApplicationController
end
def split_params
- params.require(:split).permit(splits: [ :name, :amount, :category_id, :excluded ])
+ params.require(:split).permit(splits: [ :name, :amount, :category_id, :merchant_id, :excluded, tag_ids: [] ])
+ end
+
+ def set_form_options
+ @categories = grouped_categories
+ @merchants = Current.family.available_merchants_for(Current.user).alphabetically
+ @tags = Current.family.tags.alphabetically
+ end
+
+ # Builds Entry#split! input from submitted params. Category, merchant and tag ids are
+ # re-scoped to the current family (Entry::SplitReferences, shared with rule-driven splits)
+ # rather than trusted, so a crafted request can't attach another family's records.
+ def build_splits
+ references = Entry::SplitReferences.for_user(Current.family, Current.user)
+
+ raw_splits = split_params[:splits] || []
+ raw_splits = raw_splits.values if raw_splits.respond_to?(:values)
+
+ raw_splits.map do |s|
+ {
+ name: s[:name],
+ amount: s[:amount].to_d * -1,
+ excluded: s[:excluded],
+ **references.scope(category_id: s[:category_id], merchant_id: s[:merchant_id], tag_ids: s[:tag_ids])
+ }
+ end
end
def grouped_categories
diff --git a/app/helpers/styled_form_builder.rb b/app/helpers/styled_form_builder.rb
index 688e4cd7b9..bb2e2a348a 100644
--- a/app/helpers/styled_form_builder.rb
+++ b/app/helpers/styled_form_builder.rb
@@ -86,6 +86,7 @@ class StyledFormBuilder < ActionView::Helpers::FormBuilder
label: options[:label],
container_class: options[:container_class],
label_tooltip: options[:label_tooltip],
+ scoped_ids: options.fetch(:scoped_ids, false),
html_options: html_options
)
)
diff --git a/app/javascript/controllers/rule/actions_controller.js b/app/javascript/controllers/rule/actions_controller.js
index e121a65f2b..ee87dbc387 100644
--- a/app/javascript/controllers/rule/actions_controller.js
+++ b/app/javascript/controllers/rule/actions_controller.js
@@ -8,7 +8,8 @@ export default class extends Controller {
"actionValue",
"selectTemplate",
"multiSelectTemplate",
- "textTemplate"
+ "textTemplate",
+ "splitTemplate"
];
remove(e) {
@@ -31,12 +32,21 @@ export default class extends Controller {
// Clear any existing input elements first
this.#clearFormFields();
+ // Split uses a full-width block layout; the other types are a single inline "to <value>" field
+ this.actionValueTarget.classList.toggle("w-full", actionExecutor.type === "split");
+ this.actionValueTarget.classList.toggle("min-w-1/2", actionExecutor.type !== "split");
+ this.actionValueTarget.classList.toggle("flex", actionExecutor.type !== "split");
+ this.actionValueTarget.classList.toggle("items-center", actionExecutor.type !== "split");
+ this.actionValueTarget.classList.toggle("gap-2", actionExecutor.type !== "split");
+
if (actionExecutor.type === "select") {
this.#buildSelectFor(actionExecutor);
} else if (actionExecutor.type === "multi_select") {
this.#buildMultiSelectFor();
} else if (actionExecutor.type === "text") {
this.#buildTextInputFor();
+ } else if (actionExecutor.type === "split") {
+ this.#buildSplitBuilderFor();
} else {
// Hide for any type that doesn't need a value (e.g. function)
this.#hideActionValue();
@@ -104,4 +114,13 @@ export default class extends Controller {
this.actionValueTarget.appendChild(template);
this.actionValueTarget.classList.remove("hidden");
}
+
+ #buildSplitBuilderFor() {
+ // Clone the (blank) split builder template. The nested rule--split-action controller
+ // connects automatically once the content is attached to the document.
+ const template = this.splitTemplateTarget.content.cloneNode(true);
+
+ this.actionValueTarget.appendChild(template);
+ this.actionValueTarget.classList.remove("hidden");
+ }
}
diff --git a/app/javascript/controllers/rule/split_action_controller.js b/app/javascript/controllers/rule/split_action_controller.js
new file mode 100644
index 0000000000..528fd1d4f5
--- /dev/null
+++ b/app/javascript/controllers/rule/split_action_controller.js
@@ -0,0 +1,188 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Connects to data-controller="rule--split-action"
+// Split rows use real, individually-named form fields (rendered server-side), so this
+// controller only handles adding/removing rows and the live summary indicator — it never
+// needs to serialize anything into a hidden field itself.
+//
+// Each row carries its own type (fixed or percentage) rather than the action having a single
+// mode — mirrors Rule::ActionExecutor::SplitTransaction, where fixed splits are subtracted
+// from the transaction total first and percentage splits then divide whatever's left.
+export default class extends Controller {
+ static targets = ["row", "rowTemplate", "rowsContainer", "summary", "typeSelect", "shareInput"];
+ static values = { fixedLabel: String };
+
+ static MIN_ROWS = 2;
+ static AMOUNT_TOLERANCE = 0.01;
+
+ connect() {
+ this.updateSummary();
+ this.#observeConditions();
+ }
+
+ disconnect() {
+ this.conditionsObserver?.disconnect();
+ this.form?.removeEventListener("input", this.boundUpdateSummary);
+ this.form?.removeEventListener("change", this.boundUpdateSummary);
+ }
+
+ addRow(e) {
+ e.preventDefault();
+ // Without this, the click bubbles up to the dialog's "click outside to close"
+ // listener and (harmlessly on its own) counts as an outside click.
+ e.stopPropagation();
+
+ // Seeded from Date.now() (so it can't collide with existing server-rendered row indices,
+ // e.g. 0/1/2 for an already-configured split action) but incremented monotonically from
+ // there — two rows added within the same millisecond would otherwise get the same index,
+ // producing duplicate field names that silently drop one row.
+ this.nextRowIndex ??= Date.now();
+ // "SPLIT_ROW_PLACEHOLDER", not "ROW_IDX_PLACEHOLDER": this controller's template can itself
+ // be nested inside a brand-new action added by rules_controller.js#addAction(), which does
+ // its own global replace of "IDX_PLACEHOLDER" — a substring of "ROW_IDX_PLACEHOLDER" — for
+ // the action's own index, corrupting this placeholder before this code ever runs.
+ const html = this.rowTemplateTarget.innerHTML.replaceAll(
+ "SPLIT_ROW_PLACEHOLDER",
+ this.nextRowIndex++,
+ );
+ this.rowsContainerTarget.insertAdjacentHTML("beforeend", html);
+ this.updateSummary();
+ }
+
+ removeRow(e) {
+ e.preventDefault();
+ // Critical here: this handler removes the clicked element from the DOM. Without
+ // stopPropagation, the click event keeps bubbling to the dialog's "click outside to
+ // close" listener, which checks whether e.target is still contained in the dialog —
+ // but the target we just removed no longer is, so the whole "New rule" dialog would
+ // incorrectly close itself.
+ e.stopPropagation();
+
+ if (this.rowTargets.length <= this.constructor.MIN_ROWS) return;
+
+ e.target.closest("[data-rule--split-action-target='row']").remove();
+ this.updateSummary();
+ }
+
+ updateSummary() {
+ const rows = this.rowTargets.map((row) => ({
+ type: row.querySelector("[data-rule--split-action-target='typeSelect']")?.value ?? "percentage",
+ share: Number.parseFloat(row.querySelector("[data-rule--split-action-target='shareInput']")?.value) || 0,
+ }));
+
+ const fixedRows = rows.filter((row) => row.type === "fixed");
+ const percentageRows = rows.filter((row) => row.type === "percentage");
+ const fixedTotal = fixedRows.reduce((sum, row) => sum + row.share, 0);
+ const percentageTotal = percentageRows.reduce((sum, row) => sum + row.share, 0);
+
+ const parts = [];
+ let hasTarget = false;
+ let balanced = true;
+
+ if (fixedRows.length > 0) {
+ if (percentageRows.length > 0) {
+ // Percentage rows absorb whatever's left after the fixed amounts, so there's nothing
+ // fixed-specific to balance against here (the sum just needs individually-positive
+ // rows, already enforced by the min="0" input constraint).
+ parts.push(`${fixedTotal.toFixed(2)} ${this.fixedLabelValue}`);
+ } else {
+ // No percentage rows: every split is a fixed amount, so the total needs to match the
+ // rule's "Amount equal to X" condition (if one is set) — that's the only thing that
+ // guarantees every matching transaction has the same total for the fixed amounts to
+ // add up to.
+ const targetAmount = this.#findExactAmountConditionValue();
+
+ if (targetAmount === null) {
+ parts.push(fixedTotal.toFixed(2));
+ } else {
+ hasTarget = true;
+ balanced = Math.abs(fixedTotal - targetAmount) < this.constructor.AMOUNT_TOLERANCE;
+ parts.push(`${fixedTotal.toFixed(2)} / ${targetAmount.toFixed(2)}`);
+ }
+ }
+ }
+
+ if (percentageRows.length > 0) {
+ hasTarget = true;
+ const percentageBalanced = Math.abs(percentageTotal - 100) < this.constructor.AMOUNT_TOLERANCE;
+ balanced &&= percentageBalanced;
+ parts.push(`${percentageTotal.toFixed(2)}%`);
+ }
+
+ this.summaryTarget.textContent = parts.join(" + ");
+
+ // Nothing to compare against yet (pure fixed splits with no amount condition) — leave
+ // neutral instead of flagging red before the user has finished setting up the rule.
+ if (!hasTarget) {
+ this.summaryTarget.classList.remove("text-destructive", "text-success");
+ return;
+ }
+
+ this.summaryTarget.classList.toggle("text-destructive", !balanced);
+ this.summaryTarget.classList.toggle("text-success", balanced);
+ }
+
+ // A pure-fixed summary compares against the rule's "Amount = X" condition, which lives
+ // outside this controller's element. Re-run the summary when any form field changes, and
+ // when condition rows are added, removed (hidden) or re-rendered (e.g. a new value field
+ // after switching the operator), so the live feedback never goes stale.
+ #observeConditions() {
+ this.form = this.element.closest("form");
+ if (!this.form) return;
+
+ this.boundUpdateSummary = () => this.updateSummary();
+ this.form.addEventListener("input", this.boundUpdateSummary);
+ this.form.addEventListener("change", this.boundUpdateSummary);
+
+ const conditionsList = this.form.querySelector("[data-rules-target='conditionsList']");
+ if (!conditionsList) return;
+
+ this.conditionsObserver = new MutationObserver(this.boundUpdateSummary);
+ this.conditionsObserver.observe(conditionsList, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ["class"],
+ });
+ }
+
+ // Looks across the whole form (not just this controller's element) for a
+ // non-deleted "transaction amount = X" condition and returns its numeric value,
+ // or null if no such condition currently exists.
+ #findExactAmountConditionValue() {
+ const conditionRows = document.querySelectorAll("[data-controller~='rule--conditions']");
+
+ for (const row of conditionRows) {
+ if (row.classList.contains("hidden")) continue;
+
+ const typeSelect = row.querySelector("select[name*='[condition_type]']");
+ const operatorSelect = row.querySelector("select[name*='[operator]']");
+ if (typeSelect?.value !== "transaction_amount" || operatorSelect?.value !== "=") continue;
+
+ // Mirrors Rule::Action#exact_amount_condition_value, which only accepts this
+ // condition at the top level or nested inside "and" compounds — an "or"/"any"
+ // compound doesn't guarantee it holds for every matching transaction.
+ if (!this.#isWithinAndOnlyAncestry(row)) continue;
+
+ const valueInput = row.querySelector("[name*='[value]']");
+ const amount = Number.parseFloat(valueInput?.value);
+ if (Number.isFinite(amount)) return amount;
+ }
+
+ return null;
+ }
+
+ #isWithinAndOnlyAncestry(row) {
+ let subList = row.parentElement?.closest("[data-rule--conditions-target='subConditionsList']");
+
+ while (subList) {
+ const compoundRow = subList.closest("[data-controller~='rule--conditions']");
+ const operatorSelect = compoundRow?.querySelector("select[name*='[operator]']");
+ if (operatorSelect?.value !== "and") return false;
+
+ subList = compoundRow.parentElement?.closest("[data-rule--conditions-target='subConditionsList']");
+ }
+
+ return true;
+ }
+}
diff --git a/app/javascript/controllers/split_transaction_controller.js b/app/javascript/controllers/split_transaction_controller.js
index f7c9cd46b3..a815037dd6 100644
--- a/app/javascript/controllers/split_transaction_controller.js
+++ b/app/javascript/controllers/split_transaction_controller.js
@@ -1,7 +1,13 @@
import { Controller } from "@hotwired/stimulus"
+// Split rows are real, individually-named form fields rendered server-side (via the
+// "splits/row" partial) and cloned from a <template> for new rows — mirrors
+// rule--split-action, which took the same approach after a hand-rolled JS-serialized
+// blob proved fragile in practice. Cloning from the template means new rows automatically
+// pick up whatever fields the partial renders (category/merchant/tag selects included)
+// without this controller needing to know about them.
export default class extends Controller {
- static targets = ["rowsContainer", "row", "amountInput", "remaining", "remainingContainer", "error", "submitButton", "nameInput"]
+ static targets = ["rowsContainer", "row", "rowTemplate", "amountInput", "remaining", "remainingContainer", "error", "submitButton", "nameInput"]
static values = { total: Number, currency: String }
connect() {
@@ -13,96 +19,13 @@ export default class extends Controller {
}
addRow() {
- const index = this.rowCount
- const container = this.rowsContainerTarget
-
- const row = document.createElement("div")
- row.classList.add("p-3", "rounded-lg", "border", "border-secondary", "bg-container")
- row.dataset.splitTransactionTarget = "row"
-
- // Clone category select from the first row
- const existingCategorySelect = container.querySelector(".category-select-container")
- let categorySelectHTML = ""
- if (existingCategorySelect) {
- const cloned = existingCategorySelect.cloneNode(true)
-
- // Reset hidden input value and update name
- const hiddenInput = cloned.querySelector("input[type='hidden']")
- if (hiddenInput) {
- hiddenInput.value = ""
- hiddenInput.name = `split[splits][${index}][category_id]`
- }
-
- // Reset button to show placeholder text (uncategorized)
- const button = cloned.querySelector("[data-select-target='button']")
- if (button) {
- // Find the uncategorized option text from the menu
- const uncategorizedOption = cloned.querySelector("[data-value='']")
- const placeholderText = uncategorizedOption ? uncategorizedOption.dataset.filterName : "(uncategorized)"
- button.innerHTML = placeholderText
- button.setAttribute("aria-expanded", "false")
- }
-
- // Reset selected states in menu
- cloned.querySelectorAll("[role='option']").forEach(option => {
- option.setAttribute("aria-selected", "false")
- option.classList.remove("bg-container-inset")
- const checkIcon = option.querySelector(".check-icon")
- if (checkIcon) checkIcon.classList.add("hidden")
- })
-
- // Select the blank/uncategorized option
- const blankOption = cloned.querySelector("[data-value='']")
- if (blankOption) {
- blankOption.setAttribute("aria-selected", "true")
- blankOption.classList.add("bg-container-inset")
- const checkIcon = blankOption.querySelector(".check-icon")
- if (checkIcon) checkIcon.classList.remove("hidden")
- }
-
- // Ensure menu is hidden
- const menu = cloned.querySelector("[data-select-target='menu']")
- if (menu && !menu.classList.contains("hidden")) {
- menu.classList.add("hidden")
- }
-
- categorySelectHTML = cloned.outerHTML
- }
-
- row.innerHTML = `
- <div class="flex flex-wrap md:flex-nowrap items-end gap-2">
- <div class="w-full md:flex-1 md:w-auto min-w-0 md:min-w-28">
- <label class="text-xs font-medium text-secondary uppercase tracking-wide block mb-1">Name</label>
- <input type="text"
- name="split[splits][${index}][name]"
- placeholder="Split name"
- class="form-field__input border border-secondary rounded-md px-2.5 py-1.5 w-full text-sm text-primary bg-container"
- required
- autocomplete="off"
- data-split-transaction-target="nameInput">
- </div>
- <div class="flex-1 md:flex-none md:w-28">
- <label class="text-xs font-medium text-secondary uppercase tracking-wide block mb-1">Amount</label>
- <input type="number"
- name="split[splits][${index}][amount]"
- placeholder="0.00"
- step="0.01"
- class="form-field__input border border-secondary rounded-md px-2.5 py-1.5 w-full text-sm text-primary bg-container"
- required
- autocomplete="off"
- data-split-transaction-target="amountInput"
- data-action="input->split-transaction#updateRemaining">
- </div>
- ${categorySelectHTML}
- <button type="button"
- class="w-8 h-8 shrink-0 flex items-center justify-center rounded-md text-secondary hover:text-primary hover:bg-surface-hover transition-colors"
- data-action="click->split-transaction#removeRow">
- <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
- </button>
- </div>
- `
-
- container.appendChild(row)
+ // Seeded from Date.now() (so it can't collide with existing server-rendered row indices,
+ // e.g. 0/1/2 for an already-split transaction's children) but incremented monotonically
+ // from there — two rows added within the same millisecond would otherwise get the same
+ // index, producing duplicate field names that silently drop one row.
+ this.nextRowIndex ??= Date.now()
+ const html = this.rowTemplateTarget.innerHTML.replaceAll("ROW_IDX_PLACEHOLDER", this.nextRowIndex++)
+ this.rowsContainerTarget.insertAdjacentHTML("beforeend", html)
this.updateRemaining()
}
@@ -111,20 +34,10 @@ export default class extends Controller {
const row = event.target.closest("[data-split-transaction-target='row']")
if (row && this.rowCount > 1) {
row.remove()
- this.reindexRows()
this.updateRemaining()
}
}
- reindexRows() {
- this.rowTargets.forEach((row, index) => {
- // Update input names (including hidden inputs inside category select)
- row.querySelectorAll("[name]").forEach(input => {
- input.name = input.name.replace(/splits\[\d+\]/, `splits[${index}]`)
- })
- })
- }
-
updateRemaining() {
const total = this.totalValue
const sum = this.amountInputTargets.reduce((acc, input) => {
diff --git a/app/models/assistant/function/get_rule_options.rb b/app/models/assistant/function/get_rule_options.rb
index 36370572cb..29158dc7ad 100644
--- a/app/models/assistant/function/get_rule_options.rb
+++ b/app/models/assistant/function/get_rule_options.rb
@@ -39,7 +39,7 @@ class Assistant::Function::GetRuleOptions < Assistant::Function
{
success: true,
conditions: rule.condition_filters.map { |filter| describe_filter(filter) } + [ compound_option ],
- actions: rule.action_executors.reject { |e| BLOCKED_ACTION_TYPES.include?(e.key) }.map { |executor| describe_executor(executor) }
+ actions: rule.action_executors.reject { |e| (BLOCKED_ACTION_TYPES + SETTINGS_ONLY_ACTION_TYPES).include?(e.key) }.map { |executor| describe_executor(executor) }
}
end
diff --git a/app/models/assistant/function/rule_support.rb b/app/models/assistant/function/rule_support.rb
index 4cfb00642f..9534c72333 100644
--- a/app/models/assistant/function/rule_support.rb
+++ b/app/models/assistant/function/rule_support.rb
@@ -18,6 +18,8 @@ module Assistant::Function::RuleSupport
# AI-backed actions cost money per transaction; the web UI shows a cost
# estimate before applying them, which this surface cannot do yet.
BLOCKED_ACTION_TYPES = %w[auto_categorize auto_detect_merchants].freeze
+ # Actions whose value this surface can't describe yet (the split editor builds a JSON config).
+ SETTINGS_ONLY_ACTION_TYPES = %w[split_transaction].freeze
# Ids are resolved to names by these lookups, keyed by condition or action type.
ACCOUNT_KEYS = %w[transaction_account set_as_transfer_or_payment].freeze
@@ -195,6 +197,7 @@ module Assistant::Function::RuleSupport
type = attrs["action_type"].to_s
return [ "#{path}: #{type} calls an AI model and is not available here; add it in Settings > Rules." ] if BLOCKED_ACTION_TYPES.include?(type)
+ return [ "#{path}: #{type} is not available here; add it in Settings > Rules." ] if SETTINGS_ONLY_ACTION_TYPES.include?(type)
executor = rule.action_executors.find { |e| e.key == type }
return [ "#{path}: unknown action_type '#{type}'. See get_rule_options." ] unless executor
diff --git a/app/models/entry.rb b/app/models/entry.rb
index e3429da253..816dfe6a90 100644
--- a/app/models/entry.rb
+++ b/app/models/entry.rb
@@ -464,15 +464,56 @@ class Entry < ApplicationRecord
child_entries.exists?
end
+ # Splits this entry unless it stopped being splittable. Two callers (the split dialog, two
+ # split rules, a rule and an API request) can both pass a splittable? check before either
+ # inserts children, and split! only validates its own amounts, so without the lock both sets
+ # of children would land and the amount would count twice. A provider sync can also mark the
+ # transaction pending or a transfer in between, so those are re-checked too. Returns true
+ # when it split.
+ def split_once!(splits, lock_attributes: false)
+ with_split_lock do |txn|
+ next false if split_parent? || excluded? || txn&.transfer? || txn&.pending?
+
+ split!(splits, lock_attributes: lock_attributes)
+ true
+ end
+ end
+
+ # Replaces the children of a split under the same lock, so a concurrent unsplit can't be undone
+ # and two edits can't both insert children. Returns false when the entry is no longer a split
+ # parent. Editing an existing split doesn't re-check pending/transfer: it creates no new split.
+ def resplit!(splits)
+ with_split_lock do
+ next false unless split_parent?
+
+ unsplit!
+ split!(splits)
+ true
+ end
+ end
+
+ # Unsplits under the same lock. Returns false when another caller already did.
+ def unsplit_once!
+ with_split_lock do
+ next false unless split_parent?
+
+ unsplit!
+ true
+ end
+ end
+
def split_child?
parent_entry_id.present?
end
# Splits this entry into child entries. Marks parent as excluded.
#
- # @param splits [Array<Hash>] array of { name:, amount:, category_id:, excluded: } hashes
+ # @param splits [Array<Hash>] array of { name:, amount:, category_id:, merchant_id:, tag_ids:, excluded: } hashes.
+ # merchant_id and tag_ids are optional per split and fall back to the parent's merchant / no tags.
+ # @param lock_attributes [Boolean] locks the category and merchant each split sets on its child, so
+ # rules further down (or a later run) don't overwrite them. Tags are only ever added by rules.
# @return [Array<Entry>] the created child entries
- def split!(splits)
+ def split!(splits, lock_attributes: false)
total = splits.sum { |s| s[:amount].to_d }
unless total == amount
raise ActiveRecord::RecordInvalid.new(self), "Split amounts must sum to parent amount (expected #{amount}, got #{total})"
@@ -482,9 +523,14 @@ class Entry < ApplicationRecord
children = splits.map do |split_attrs|
child_transaction = Transaction.new(
category_id: split_attrs[:category_id],
- merchant_id: entryable.try(:merchant_id),
+ merchant_id: split_attrs[:merchant_id].presence || entryable.try(:merchant_id),
+ tag_ids: split_attrs[:tag_ids] || [],
kind: entryable.try(:kind)
)
+ if lock_attributes
+ locked_at = Time.current
+ child_transaction.locked_attributes = split_attrs.slice(:category_id, :merchant_id).compact_blank.keys.index_with { locked_at }
+ end
child_entries.create!(
account: account,
@@ -601,6 +647,20 @@ class Entry < ApplicationRecord
end
private
+ # Takes FOR UPDATE on the transaction row, then on this entry (lock! also reloads both), always
+ # in that order so the split methods can't deadlock each other. Yields the transaction, or nil
+ # for other entryables.
+ #
+ # Explicit transaction + lock!, not with_lock: Entry#transaction is the delegated_type
+ # accessor for the Transaction entryable, so with_lock silently never yields.
+ def with_split_lock
+ self.class.transaction do
+ txn = entryable if entryable.is_a?(Transaction)
+ txn&.lock!
+ lock!
+ yield txn
+ end
+ end
# Remembers the earliest date this entry had before any save that changed
# it, for sync_account_later to use as the sync window start.
diff --git a/app/models/entry/split_references.rb b/app/models/entry/split_references.rb
new file mode 100644
index 0000000000..e6aecc070a
--- /dev/null
+++ b/app/models/entry/split_references.rb
@@ -0,0 +1,45 @@
+# Scopes the category, merchant and tag ids of split rows to records the family may use, so a
+# crafted, foreign or since-deleted id is dropped instead of attached to a child entry. Shared by
+# manual splits (SplitsController) and rule splits (Rule::ActionExecutor::SplitTransaction).
+#
+# The merchant scope is the one difference between the two: a manual split may use any merchant
+# the user can see (available_merchants_for, which includes provider merchants on accounts they
+# can access), while a rule runs without a user and only offers family merchants in its picker.
+#
+# The API rejects a request with an unusable id instead of dropping it (a caller that sent an id
+# expects it to be stored), so it asks #unknown for the ids #scope would drop.
+class Entry::SplitReferences
+ # Manual splits: any merchant the user can see.
+ def self.for_user(family, user)
+ new(family, merchants: family.available_merchants_for(user))
+ end
+
+ def initialize(family, merchants: family.merchants)
+ @category_ids = family.categories.pluck(:id).to_set
+ @merchant_ids = merchants.pluck(:id).to_set
+ @tag_ids = family.tags.pluck(:id).to_set
+ end
+
+ def scope(category_id:, merchant_id:, tag_ids:)
+ category_id = category_id.presence
+ merchant_id = merchant_id.presence
+
+ {
+ category_id: (category_id if @category_ids.include?(category_id)),
+ merchant_id: (merchant_id if @merchant_ids.include?(merchant_id)),
+ tag_ids: Array(tag_ids).reject(&:blank?).select { |id| @tag_ids.include?(id) }.uniq
+ }
+ end
+
+ # The ids #scope would drop, as [kind, id] pairs (kind is :category, :merchant or :tag).
+ def unknown(category_id:, merchant_id:, tag_ids:)
+ category_id = category_id.presence
+ merchant_id = merchant_id.presence
+
+ unknown = []
+ unknown << [ :category, category_id ] if category_id && !@category_ids.include?(category_id)
+ unknown << [ :merchant, merchant_id ] if merchant_id && !@merchant_ids.include?(merchant_id)
+ Array(tag_ids).reject(&:blank?).uniq.each { |id| unknown << [ :tag, id ] unless @tag_ids.include?(id) }
+ unknown
+ end
+end
diff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rb
index 827b71bb16..32c4dbbd41 100644
--- a/app/models/family/data_exporter.rb
+++ b/app/models/family/data_exporter.rb
@@ -832,9 +832,45 @@ class Family::DataExporter
return resolve_multi_tag_operand(action.value)
end
+ if action.action_type == "split_transaction"
+ return { value: portable_split_value(action.value), value_ref: nil }
+ end
+
rule_operand(action.value)
end
+ # The split config is a JSON blob whose rows reference categories, merchants
+ # and tags by id. Ids only mean something inside this family, so each row
+ # carries names instead (see Rule::ActionExecutor::SplitTransaction.localize_value
+ # for the import side). Ids that no longer resolve (record deleted since the
+ # rule was saved) are dropped, matching how the executor ignores them.
+ def portable_split_value(value)
+ config = Rule::ActionExecutor::SplitTransaction.parse_config(value)
+ return value unless config
+
+ splits = config["splits"].map do |split|
+ row = split.except("category_id", "merchant_id", "tag_ids")
+ category = split_operand_record(:categories, split["category_id"])
+ merchant = split_operand_record(:merchants, split["merchant_id"])
+ tags = Array(split["tag_ids"]).filter_map { |id| split_operand_record(:tags, id) }
+
+ row["category"] = category.name if category
+ row["merchant"] = merchant.name if merchant
+ row["tags"] = tags.map(&:name) if tags.any?
+ row
+ end
+
+ # An object, not a JSON string: the CSV rule import unescapes \" inside string values,
+ # which would corrupt a nested JSON string whose names contain quotes.
+ config.merge("splits" => splits)
+ end
+
+ def split_operand_record(relation_key, id)
+ return nil unless id.is_a?(String) && uuid_like?(id)
+
+ operand_records_by_id(relation_key)[id.downcase]
+ end
+
def resolve_multi_tag_operand(value)
ids = value.to_s.split(",")
records = ids.map { |id| resolve_rule_operand_record(:tags, id, fallback_to_name: true) }
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index 27e7db9e5a..e9eaaacfd4 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -1474,6 +1474,7 @@ class Family::DataImporter
# resolution path rather than the generic scalar one below (which
# assumes value_ref is nil or a single hash).
return resolve_multi_tag_action_value(action_data) if action_type == "set_transaction_tags"
+ return resolve_split_action_value(action_data["value"]) if action_type == "split_transaction"
value = rule_operand_value(action_data)
@@ -1513,6 +1514,32 @@ class Family::DataImporter
tag_ids.join(",")
end
+ # Names resolve like the other rule actions. A raw id (older exports, hand-built files) is
+ # remapped through this import's source mappings, kept if it already belongs to the family,
+ # and otherwise dropped.
+ def resolve_split_action_value(value)
+ # Checked like every other rule text, before find_or_create can hit the database with a name.
+ unless Rule::ActionExecutor::SplitTransaction.acceptable_text?(value)
+ raise InvalidRecordError.new(record_type: "Rule", field: "value", value: "(invalid text)")
+ end
+
+ Rule::ActionExecutor::SplitTransaction.localize_value(value) do |kind, name: nil, id: nil|
+ relation = kind.to_s.pluralize.to_sym
+ next mapped_id(relation, id, record_type: kind.to_s.classify, required: false) || (id if family_record_ids(relation).include?(id)) unless name
+
+ case kind
+ when :category then find_or_create_rule_category(name).id
+ when :merchant then find_or_create_rule_merchant(name).id
+ when :tag then find_or_create_rule_tag(name).id
+ end
+ end
+ end
+
+ def family_record_ids(relation)
+ @family_record_ids ||= {}
+ @family_record_ids[relation] ||= @family.public_send(relation).pluck(:id).to_set
+ end
+
# Preloaded once per import and extended in place on cache-miss, so a
# category/merchant/tag created for an earlier record is immediately
# visible to a later record referencing the same name, instead of one
diff --git a/app/models/rule.rb b/app/models/rule.rb
index 5e7e73f52f..517da613fe 100644
--- a/app/models/rule.rb
+++ b/app/models/rule.rb
@@ -31,6 +31,7 @@ class Rule < ApplicationRecord
# Every rule must have at least 1 action
validate :min_actions
validate :no_duplicate_actions
+ validate :split_is_only_action
# Switching a rule on records the transactions it already matches as delivered,
# so an email action only reports what appears afterwards. Rule::Action seeds the
@@ -330,6 +331,14 @@ class Rule < ApplicationRecord
errors.add(:base, :duplicate_actions, types: action_types.inspect) if action_types.uniq.count != action_types.count
end
+ # Actions after a split find the parent hidden, and actions before it change only the
+ # hidden parent, so a split rule can't usefully do anything else.
+ def split_is_only_action
+ action_types = actions.reject(&:marked_for_destruction?).map(&:action_type)
+
+ errors.add(:base, :split_not_alone) if action_types.include?("split_transaction") && action_types.size > 1
+ end
+
# Validation: To keep rules simple and easy to understand, we don't allow nested compound conditions.
def no_nested_compound_conditions
return true if conditions.none? { |condition| condition.compound? }
diff --git a/app/models/rule/action.rb b/app/models/rule/action.rb
index 5d39cba9c7..3a25661dad 100644
--- a/app/models/rule/action.rb
+++ b/app/models/rule/action.rb
@@ -3,11 +3,28 @@ class Rule::Action < ApplicationRecord
SUPPORTED_ACTION_TYPES = Rule::Registry::TransactionResource.action_executor_keys.freeze
+ # Virtual attribute for the split_transaction form: `value` is a single string column, so the
+ # split builder UI posts real, individually-named fields here instead of driving a JSON blob
+ # through custom JS. build_split_value assembles them into `value` before validation runs.
+ # Each row carries its own "type" (fixed or percentage) rather than the action having a single
+ # mode — see Rule::ActionExecutor::SplitTransaction for how the two types combine.
+ attr_reader :split_rows
+
+ # split_rows isn't a tracked attribute, so assigning it must mark `value` as changing: otherwise
+ # a nested-attributes update of an existing rule skips this unchanged-looking action and the
+ # edited splits are never built or saved.
+ def split_rows=(rows)
+ @split_rows = rows
+ value_will_change! if rows.present?
+ end
+
validates :action_type, presence: true, if: -> { action_type.to_s.valid_encoding? }
# A NUL or invalid encoding is reported by DatabaseTextValidator instead.
validates :action_type, inclusion: { in: SUPPORTED_ACTION_TYPES, allow_blank: true },
if: -> { DatabaseTextValidator.acceptable?(action_type) }
validates_with DatabaseTextValidator, attributes: %i[action_type value]
+ before_validation :build_split_value, if: -> { action_type == "split_transaction" && split_rows.present? }
+ validate :split_config_valid, if: -> { action_type == "split_transaction" }
# Pre-seed (watermark): when a send_email_notification action is created — on a
# new rule OR added to an existing one — record all currently-matching
@@ -73,6 +90,9 @@ class Rule::Action < ApplicationRecord
end
def value_display
+ custom_display = executor.value_display(value)
+ return custom_display if custom_display.present?
+
return "" if value.blank?
cached_options = options
@@ -91,6 +111,76 @@ class Rule::Action < ApplicationRecord
executor.type == "multi_select" ? value.to_s.split(",") : value
end
+ def build_split_value
+ rows = split_rows.respond_to?(:values) ? split_rows.values : Array(split_rows)
+ splits = rows.map do |row|
+ {
+ type: row[:type],
+ name: row[:name],
+ share: row[:share],
+ category_id: row[:category_id].presence,
+ merchant_id: row[:merchant_id].presence,
+ tag_ids: Array(row[:tag_ids]).reject(&:blank?)
+ }
+ end
+
+ self.value = { splits: splits }.to_json
+ end
+
+ def split_config_valid
+ config_errors = Rule::ActionExecutor::SplitTransaction.config_errors(value, family: rule.family)
+ config_errors.each do |key, options|
+ errors.add(:value, key, **options)
+ end
+
+ return unless config_errors.empty?
+
+ config = Rule::ActionExecutor::SplitTransaction.parse_config(value)
+ return if Rule::ActionExecutor::SplitTransaction.has_percentage_split?(config)
+
+ # Pure fixed splits (no percentage row to absorb whatever's left) only make sense if every
+ # matching transaction has the same total, since there's nothing dynamic to cover a
+ # mismatch — require an exact "Amount =" condition whose value the fixed shares sum to.
+ exact_amount = exact_amount_condition_value
+ if exact_amount.nil?
+ errors.add(:value, :fixed_requires_exact_amount_condition)
+ else
+ total_share = config["splits"].sum { |split| BigDecimal(split["share"].to_s) }
+ if total_share != exact_amount
+ errors.add(:value, :fixed_shares_must_equal_condition_amount, amount: exact_amount)
+ end
+ end
+ end
+
+ # Fixed-amount splits only make sense if every matching transaction has the same total —
+ # otherwise the configured shares can never sum correctly for most matches (rule.apply
+ # would just silently skip them one by one). Require an exact "Amount =" condition, ANDed
+ # in (an "any"/OR compound doesn't guarantee it for every match), and return its numeric
+ # value so callers can also check the shares actually sum to it. Returns nil if no such
+ # condition exists.
+ def exact_amount_condition_value(conditions = rule.conditions)
+ conditions.reject(&:marked_for_destruction?).each do |condition|
+ if condition.compound?
+ next unless condition.operator == "and"
+ found = exact_amount_condition_value(condition.sub_conditions)
+ return found if found
+ elsif condition.condition_type == "transaction_amount" && condition.operator == "="
+ parsed = parse_condition_amount(condition.value)
+ return parsed if parsed
+ end
+ end
+
+ nil
+ end
+
+ def parse_condition_amount(value)
+ return nil if value.blank?
+
+ BigDecimal(value.to_s)
+ rescue ArgumentError, TypeError
+ nil
+ end
+
def seed_notification_baseline
return unless action_type == "send_email_notification"
return if rule.notification_baseline_taken_in_this_save?
diff --git a/app/models/rule/action_executor.rb b/app/models/rule/action_executor.rb
index 52a1cfa1f3..b21884172f 100644
--- a/app/models/rule/action_executor.rb
+++ b/app/models/rule/action_executor.rb
@@ -1,5 +1,5 @@
class Rule::ActionExecutor
- TYPES = [ "select", "multi_select", "function", "text" ]
+ TYPES = [ "select", "multi_select", "function", "text", "split" ]
def initialize(rule)
@rule = rule
@@ -60,6 +60,13 @@ class Rule::ActionExecutor
}
end
+ # Executors with a non-trivial value format (e.g. structured JSON) can override this
+ # to provide a human-readable summary for the rule list view. Returning nil falls back
+ # to the default (options-based) display logic in Rule::Action#value_display.
+ def value_display(value)
+ nil
+ end
+
protected
# Helper method to track modified count during enrichment
# The block should return true if the resource was modified, false otherwise
diff --git a/app/models/rule/action_executor/split_transaction.rb b/app/models/rule/action_executor/split_transaction.rb
new file mode 100644
index 0000000000..d86b7f6ef3
--- /dev/null
+++ b/app/models/rule/action_executor/split_transaction.rb
@@ -0,0 +1,362 @@
+class Rule::ActionExecutor::SplitTransaction < Rule::ActionExecutor
+ # Per-split type, not a single mode for the whole action: a fixed split takes a literal
+ # amount off the top, a percentage split takes a share of whatever's left after all fixed
+ # splits are subtracted. Fixed splits are always resolved first, regardless of row order.
+ TYPES = [ "fixed", "percentage" ].freeze
+ # entries.amount is decimal(19,4).
+ AMOUNT_SCALE = 4
+ REFERENCE_ERRORS = { category: :split_category_invalid, merchant: :split_merchant_invalid, tag: :split_tags_invalid }.freeze
+ MIN_SPLITS = 2
+ MAX_SPLITS = 20
+ PERCENTAGE_TOTAL_TOLERANCE = 0.01
+
+ def type
+ "split"
+ end
+
+ # Overrides the base class's nil (the `options` contract is for "select"-type executors,
+ # which the split type isn't). Keeping it nil avoids duplicating the full category list into
+ # every action row's data-rule--actions-action-executors-value attribute.
+ def options
+ nil
+ end
+
+ def category_options
+ family.categories.alphabetically.pluck(:name, :id)
+ end
+
+ def merchant_options
+ family.merchants.alphabetically.pluck(:name, :id)
+ end
+
+ # Records, not [name, id] pairs: DS::TagSelect renders each tag's color.
+ def tag_records
+ family.tags.alphabetically
+ end
+
+ def value_display(value)
+ config = self.class.parse_config(value)
+ return nil unless config
+
+ I18n.t("rules.actions.split.summary", count: config["splits"].size)
+ end
+
+ def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
+ config = self.class.parse_config(value)
+ return 0 unless config
+
+ # Children of an earlier split and excluded entries are never splittable;
+ # filtering them here saves a splittable? check per row on every run.
+ scope = transaction_scope.with_entry.where(entries: { parent_entry_id: nil, excluded: false })
+ # Resolved once per rule application (not per transaction) since the scope shares one family.
+ references = Entry::SplitReferences.new(family)
+
+ unless ignore_attribute_locks
+ # Filter by entry's locked_attributes, not transaction's
+ # Since excluded is on Entry, not Transaction, we need to check entries.locked_attributes
+ scope = scope.where.not(
+ Arel.sql("entries.locked_attributes ? 'excluded'")
+ )
+ end
+
+ skipped = []
+
+ modified_count = count_modified_resources(scope) do |txn|
+ next false unless txn.splittable?
+
+ entry = txn.entry
+ splits = self.class.build_splits(config, entry.amount, references, precision: self.class.amount_precision(entry.currency))
+
+ if splits.nil?
+ skipped << { transaction_id: txn.id, entry_id: entry.id, reason: "unresolvable_split_amounts", entry_amount: entry.amount.to_s }
+ next false
+ end
+
+ begin
+ # Two split rules (or a manual apply and a queued run) can reach the
+ # same transaction at once; split_once! locks the parent and skips it
+ # if the other run already split it (or it was excluded meanwhile).
+ # The lock keeps rules further down from overwriting the children's categories.
+ next false unless entry.split_once!(splits, lock_attributes: true)
+
+ entry.sync_account_later
+ true
+ rescue ActiveRecord::RecordInvalid => e
+ skipped << { transaction_id: txn.id, entry_id: entry.id, reason: "record_invalid", errors: e.record.errors.full_messages }
+ false
+ end
+ end
+
+ log_skipped_transactions(skipped, rule_run:) if skipped.any?
+
+ modified_count
+ end
+
+ class << self
+ # Stage 1 validation: static structural checks that don't depend on any particular
+ # matching transaction's amount. Used by Rule::Action to reject bad configs at save time.
+ # Returns an array of [i18n_key, interpolation_options] tuples (empty when valid), so the
+ # caller can render translated messages via errors.add(:value, key, **options).
+ def config_errors(value, family:)
+ config = parse_config_strict(value)
+ return [ [ :invalid_config, {} ] ] unless config
+
+ errors = []
+ splits = config["splits"]
+
+ unless splits.is_a?(Array) && splits.size.between?(MIN_SPLITS, MAX_SPLITS)
+ errors << [ :invalid_split_count, { min: MIN_SPLITS, max: MAX_SPLITS } ]
+ return errors
+ end
+
+ references = Entry::SplitReferences.new(family)
+
+ total_percentage = 0
+ has_percentage = false
+
+ # Rows come from a JSON blob, so a crafted request can put anything here (e.g. null).
+ # Reject non-object rows up front rather than raising on split["name"] below.
+ unless splits.all? { |split| split.is_a?(Hash) }
+ errors << [ :invalid_config, {} ]
+ return errors
+ end
+
+ splits.each_with_index do |split, index|
+ name = split["name"]
+ type = split["type"]
+ share = parse_decimal(split["share"])
+ position = index + 1
+
+ # A NUL byte or broken UTF-8 would only fail once the rule runs and the child is saved.
+ # Checked first: blank? raises on broken UTF-8.
+ if !DatabaseTextValidator.acceptable?(name)
+ errors << [ :split_name_invalid, { index: position } ]
+ elsif name.blank?
+ errors << [ :split_name_required, { index: position } ]
+ elsif name.to_s.length > 255
+ errors << [ :split_name_too_long, { index: position } ]
+ end
+ errors << [ :split_type_invalid, { index: position } ] unless TYPES.include?(type)
+
+ # A fixed share with more decimals than the amount columns hold would
+ # be stored rounded, and the children would no longer sum to the parent.
+ if share.nil? || share <= 0 || (type == "fixed" && share.round(AMOUNT_SCALE) != share)
+ errors << [ :split_share_invalid, { index: position } ]
+ elsif type == "percentage"
+ has_percentage = true
+ total_percentage += share
+ end
+
+ unknown = references.unknown(category_id: split["category_id"], merchant_id: split["merchant_id"], tag_ids: split["tag_ids"])
+ unknown.map(&:first).uniq.each do |kind|
+ errors << [ REFERENCE_ERRORS.fetch(kind), { index: position } ]
+ end
+ end
+
+ if has_percentage && errors.empty? && (total_percentage - 100).abs > PERCENTAGE_TOTAL_TOLERANCE
+ errors << [ :percentages_must_total_100, { total: ActiveSupport::NumberHelper.number_to_rounded(total_percentage, precision: 2, strip_insignificant_zeros: true) } ]
+ end
+
+ errors
+ end
+
+ # Parses the JSON value without raising. Returns nil if malformed or structurally incomplete.
+ def parse_config(value)
+ config = parse_config_strict(value)
+ return nil unless config
+ return nil unless config["splits"].is_a?(Array) && config["splits"].size >= MIN_SPLITS
+ return nil unless config["splits"].all? { |split| split.is_a?(Hash) }
+
+ config
+ end
+
+ # Rebuilds an imported split config against the importing family. Exports carry names
+ # ("category", "merchant", "tags", see Family::DataExporter#portable_split_value) because ids
+ # don't survive a move to another family. Each reference is resolved through the block,
+ # called as (kind, name:) for a name or (kind, id:) for a raw id, with kind :category,
+ # :merchant or :tag; it returns the local id, or nil to drop a stale or foreign id instead of
+ # failing the whole import on save. Unparseable values are returned as a string unchanged so
+ # Rule::Action's validation can report them.
+ def localize_value(value, &resolve)
+ raw = value.is_a?(Hash) || value.is_a?(Array) ? value.to_json : value.to_s
+ config = parse_config(raw)
+ return raw unless config
+
+ splits = config["splits"].map do |split|
+ split.except("category", "merchant", "tags").merge(
+ "category_id" => localize_reference(split, "category", :category, &resolve),
+ "merchant_id" => localize_reference(split, "merchant", :merchant, &resolve),
+ "tag_ids" => localize_tags(split, &resolve)
+ )
+ end
+
+ config.merge("splits" => splits).to_json
+ end
+
+ # Digits a percentage share is rounded to: the currency's minor unit (0 for JPY, 3 for KWD),
+ # capped at the 4 decimals entries.amount stores (crypto currencies list 8), so children that
+ # sum to the parent in memory still do once saved. Unknown codes fall back to cents.
+ def amount_precision(currency)
+ [ Money::Currency.new(currency).default_precision, AMOUNT_SCALE ].min
+ rescue Money::Currency::UnknownCurrencyError
+ 2
+ end
+
+ # True when every text inside an imported split value (row names, category/merchant/tag names)
+ # can be stored. A JSON string hides NUL bytes as \u0000 escapes, so it is checked decoded.
+ def acceptable_text?(value)
+ decoded = value.is_a?(String) ? JSON.parse(value) : value
+ DatabaseTextValidator.acceptable?(decoded)
+ rescue JSON::ParserError
+ DatabaseTextValidator.acceptable?(value)
+ end
+
+ # True if the config has at least one percentage-type split. Pure-fixed configs need an
+ # exact-amount rule condition (see Rule::Action#split_config_valid); configs with a
+ # percentage split don't, since the percentage share(s) always absorb whatever's left after
+ # fixed splits, adapting automatically to any matching transaction's amount.
+ def has_percentage_split?(config)
+ config["splits"].any? { |split| split["type"] == "percentage" }
+ end
+
+ # Stage 2: translates the rule's static config into concrete Entry#split! input for one
+ # specific matching transaction. Returns nil if the config can't be applied to this amount
+ # (e.g. fixed splits don't leave a positive remainder for the percentage splits to divide)
+ # rather than raising, so the caller can skip just this transaction and keep processing the
+ # rest of the scope.
+ #
+ # precision comes from amount_precision, so a percentage share never produces a fraction of
+ # the currency's smallest unit.
+ def build_splits(config, entry_amount, references, precision: 2)
+ raw_splits = config["splits"]
+ sign = entry_amount.negative? ? -1 : 1
+ total_magnitude = entry_amount.abs
+
+ fixed_indices = []
+ percentage_indices = []
+ raw_splits.each_with_index do |split, index|
+ case split["type"]
+ when "fixed" then fixed_indices << index
+ when "percentage" then percentage_indices << index
+ else return nil
+ end
+ end
+
+ amounts = Array.new(raw_splits.size)
+
+ fixed_total = 0
+ fixed_indices.each do |index|
+ amount = parse_decimal(raw_splits[index]["share"])
+ return nil if amount.nil?
+ amounts[index] = amount
+ fixed_total += amount
+ end
+
+ remaining = total_magnitude - fixed_total
+
+ if percentage_indices.empty?
+ # Pure fixed splits only make sense if this transaction's total is exactly the fixed
+ # splits' sum — there's nothing dynamic to absorb a mismatch (enforced at save time by
+ # requiring a matching exact-amount rule condition, see Rule::Action).
+ return nil unless fixed_total == total_magnitude
+ else
+ # Fixed splits ate more than (or all of) the transaction total, leaving nothing for the
+ # percentage splits to divide.
+ return nil if remaining <= 0
+
+ percentages = percentage_indices.map { |index| parse_decimal(raw_splits[index]["share"]) }
+ return nil if percentages.any?(&:nil?)
+
+ running_remaining = remaining
+ percentage_indices.each_with_index do |split_index, position|
+ if position == percentage_indices.size - 1
+ amounts[split_index] = running_remaining
+ else
+ share_amount = (remaining * percentages[position] / 100).round(precision)
+ amounts[split_index] = share_amount
+ running_remaining -= share_amount
+ end
+ end
+
+ # The last percentage split absorbs whatever's left after rounding the others to the minor unit,
+ # which can go non-positive if per-row rounding drift stacks up (many splits, large
+ # amount, tiny trailing percentage). Bail rather than create a zero/negative-amount
+ # child entry.
+ return nil if percentage_indices.any? { |index| amounts[index] <= 0 }
+ end
+
+ # Ids are re-resolved against current family state (references, built once per rule
+ # application) rather than trusting the cached JSON, since any of them may have been
+ # deleted since the rule was saved.
+ raw_splits.each_with_index.map do |split, index|
+ {
+ name: split["name"],
+ amount: amounts[index] * sign,
+ **references.scope(category_id: split["category_id"], merchant_id: split["merchant_id"], tag_ids: split["tag_ids"])
+ }
+ end
+ end
+
+ private
+ def parse_config_strict(value)
+ return nil if value.blank?
+
+ parsed = JSON.parse(value)
+ return nil unless parsed.is_a?(Hash)
+
+ parsed
+ rescue JSON::ParserError
+ nil
+ end
+
+ def localize_reference(split, key, kind)
+ name = split[key].to_s.strip
+ return yield(kind, name: name) if name.present?
+
+ id = split["#{key}_id"].to_s.strip.downcase
+ yield(kind, id: id) if id.present?
+ end
+
+ # Tags may also come as one comma-separated string, like set_transaction_tags values.
+ def localize_tags(split)
+ ids = if split.key?("tags")
+ names = split["tags"].is_a?(String) ? Rule::Action.decode_multi_value_names(split["tags"]) : Array(split["tags"])
+ names.map { |name| name.to_s.strip }.reject(&:blank?).map { |name| yield(:tag, name: name) }
+ else
+ Array(split["tag_ids"]).map { |id| id.to_s.strip.downcase }.reject(&:blank?).map { |id| yield(:tag, id: id) }
+ end
+
+ ids.compact.uniq
+ end
+
+ # Non-finite values ("NaN", "Infinity") parse fine but can never be a real share, and NaN
+ # slips past `share <= 0`, so treat them as unparseable.
+ def parse_decimal(value)
+ return nil if value.blank?
+
+ decimal = BigDecimal(value.to_s)
+ decimal.finite? ? decimal : nil
+ rescue ArgumentError, TypeError
+ nil
+ end
+ end
+
+ private
+ # One summary entry per rule application (not one per skipped transaction) so a
+ # misconfigured split action against a large matching scope can't flood the debug log.
+ def log_skipped_transactions(skipped, rule_run:)
+ DebugLogEntry.capture(
+ category: "rule_run",
+ level: "warn",
+ message: "split_transaction skipped #{skipped.size} transaction(s)",
+ source: self.class.name,
+ family: family,
+ metadata: {
+ rule_id: rule.id,
+ rule_run_id: rule_run&.id,
+ skipped_count: skipped.size,
+ skipped: skipped.first(20)
+ }
+ )
+ end
+end
diff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rb
index 394751a3c6..14c3982873 100644
--- a/app/models/rule/registry/transaction_resource.rb
+++ b/app/models/rule/registry/transaction_resource.rb
@@ -22,6 +22,7 @@ class Rule::Registry::TransactionResource < Rule::Registry
Rule::ActionExecutor::SetInvestmentActivityLabel,
Rule::ActionExecutor::ExcludeTransaction,
Rule::ActionExecutor::SetAsTransferOrPayment,
+ Rule::ActionExecutor::SplitTransaction,
Rule::ActionExecutor::SendEmailNotification,
Rule::ActionExecutor::AutoCategorize,
Rule::ActionExecutor::AutoDetectMerchants
diff --git a/app/models/rule/runner.rb b/app/models/rule/runner.rb
index 678d70e002..b2ad8638cb 100644
--- a/app/models/rule/runner.rb
+++ b/app/models/rule/runner.rb
@@ -155,7 +155,14 @@ class Rule::Runner
message: "Rule run failed: #{error_message}",
source: self.class.name,
family: rule.family,
- metadata: { rule_id: rule.id, rule_name: rule.name, execution_type: execution_type, error_class: error.class.name, error_message: error.message }
+ metadata: {
+ rule_id: rule.id,
+ rule_name: rule.name,
+ execution_type: execution_type,
+ error_class: error.class.name,
+ error_message: error.message,
+ backtrace: Array(error.backtrace).first(10)
+ }
)
if rule_run
diff --git a/app/models/rule_import.rb b/app/models/rule_import.rb
index 924f1b9499..44aa8d8e7f 100644
--- a/app/models/rule_import.rb
+++ b/app/models/rule_import.rb
@@ -51,6 +51,15 @@ class RuleImport < Import
'[{"condition_type":"transaction_name","operator":"like","value":"amazon"}]',
'[{"action_type":"auto_categorize"}]'
]
+
+ csv << [
+ "Split shared rent",
+ "transaction",
+ "true",
+ "",
+ '[{"condition_type":"transaction_name","operator":"like","value":"rent"}]',
+ '[{"action_type":"split_transaction","value":{"splits":[{"type":"percentage","name":"My share","share":"50","category":"Rent"},{"type":"percentage","name":"Partner share","share":"50","category":"Rent","tags":["Shared"]}]}}]'
+ ]
end
CSV.parse(csv_string, headers: true)
@@ -103,8 +112,8 @@ class RuleImport < Import
text.strip
end
- def reject_invalid_text!(value, label:)
- return if DatabaseTextValidator.acceptable?(value)
+ def reject_invalid_text!(value, label:, acceptable: DatabaseTextValidator.acceptable?(value))
+ return if acceptable
errors.add(:base, :invalid, message: "#{label} #{I18n.t("errors.messages.invalid")}")
raise ActiveRecord::RecordInvalid.new(self)
@@ -255,6 +264,8 @@ class RuleImport < Import
return value unless value.present?
+ return resolve_import_split_value(value) if action_type == "split_transaction"
+
# Map category names to UUIDs
if action_type == "set_transaction_category"
return find_or_create_category(value).id
@@ -283,6 +294,27 @@ class RuleImport < Import
names.map { |name| find_or_create_tag(name).id }.join(",")
end
+ # Names resolve like the other actions; a raw id is kept only if it belongs to the family.
+ def resolve_import_split_value(value)
+ reject_invalid_text!(value, label: Rule::Action.human_attribute_name(:value),
+ acceptable: Rule::ActionExecutor::SplitTransaction.acceptable_text?(value))
+
+ Rule::ActionExecutor::SplitTransaction.localize_value(value) do |kind, name: nil, id: nil|
+ next (id if family_record_ids(kind.to_s.pluralize.to_sym).include?(id)) unless name
+
+ case kind
+ when :category then find_or_create_category(name).id
+ when :merchant then find_or_create_merchant(name).id
+ when :tag then find_or_create_tag(name).id
+ end
+ end
+ end
+
+ def family_record_ids(relation)
+ @family_record_ids ||= {}
+ @family_record_ids[relation] ||= family.public_send(relation).pluck(:id).to_set
+ end
+
# Preloaded once per import and extended in place on cache-miss, so a
# category/merchant/tag created for an earlier row is immediately visible
# to a later row referencing the same name, instead of one query per
diff --git a/app/views/rule/actions/_action.html.erb b/app/views/rule/actions/_action.html.erb
index 6e30406a12..432e6520eb 100644
--- a/app/views/rule/actions/_action.html.erb
+++ b/app/views/rule/actions/_action.html.erb
@@ -3,7 +3,7 @@
<% action = form.object %>
<% rule = action.rule %>
-<li data-controller="rule--actions" data-rule--actions-action-executors-value="<%= rule.action_executors.to_json %>" class="flex items-center gap-3">
+<li data-controller="rule--actions" data-rule--actions-action-executors-value="<%= rule.action_executors.to_json %>" class="<%= class_names("flex gap-3", action.executor.type == "split" ? "items-start" : "items-center") %>">
<%= form.hidden_field :_destroy, value: false, data: { rule__actions_target: "destroyField" } %>
<div class="grid grid-cols-1 gap-2 items-center h-full w-full">
@@ -11,11 +11,20 @@
<%= form.select :action_type, rule.action_executors.map { |executor| [ executor.label, executor.key ] }, {}, data: { action: "rule--actions#handleActionTypeChange" } %>
</div>
- <%= tag.div class: class_names("min-w-1/2 flex items-center gap-2", { "hidden": action.executor.type == "function" }),
+ <%
+ action_value_classes = if action.executor.type == "split"
+ "w-full"
+ else
+ "min-w-1/2 flex items-center gap-2"
+ end
+ %>
+ <%= tag.div class: class_names(action_value_classes, { "hidden": action.executor.type == "function" }),
data: { rule__actions_target: "actionValue" } do %>
<%# Initial rendering based on the action executor type. %>
<%# Subsequent renders are injected by the Stimulus controller, which uses the templates from below. %>
- <span class="font-medium text-primary uppercase text-xs"><%= t("rules.actions.to_label") %></span>
+ <% unless action.executor.type == "split" %>
+ <span class="font-medium text-primary uppercase text-xs"><%= t("rules.actions.to_label") %></span>
+ <% end %>
<% if action.executor.type == "select" %>
<%= form.select :value, action.options || [], {} %>
<% elsif action.executor.type == "multi_select" %>
@@ -28,6 +37,8 @@
) %>
<% elsif action.executor.type == "text" %>
<%= form.text_field :value, placeholder: t("rules.actions.value_placeholder") %>
+ <% elsif action.executor.type == "split" %>
+ <%= render "rule/actions/split_builder", form: form, action: action %>
<% end %>
<% end %>
</div>
@@ -60,5 +71,9 @@
<%= form.text_field :value, placeholder: t("rules.actions.value_placeholder") %>
</template>
+ <template data-rule--actions-target="splitTemplate">
+ <%= render "rule/actions/split_builder", form: form, action: action, blank: true %>
+ </template>
+
<%# The function type doesn't need an input, so no template is required.%>
</li>
diff --git a/app/views/rule/actions/_split_builder.html.erb b/app/views/rule/actions/_split_builder.html.erb
new file mode 100644
index 0000000000..2a8debb6bd
--- /dev/null
+++ b/app/views/rule/actions/_split_builder.html.erb
@@ -0,0 +1,46 @@
+<%# locals: (form:, action:, blank: false) %>
+
+<%
+ config = blank ? nil : Rule::ActionExecutor::SplitTransaction.parse_config(action.value)
+ config ||= { "splits" => [ { "type" => "percentage" }, { "type" => "percentage" } ] }
+ split_executor = action.rule.registry.get_executor!("split_transaction")
+ categories = split_executor.category_options
+ merchants = split_executor.merchant_options
+ tags = split_executor.tag_records
+%>
+
+<div class="flex flex-col gap-2 w-full min-w-0"
+ data-controller="rule--split-action"
+ data-rule--split-action-fixed-label-value="<%= t("rules.actions.split.fixed_summary_label") %>">
+ <p class="text-xs text-secondary">
+ <%= t("rules.actions.split.hint") %>
+ </p>
+
+ <div data-rule--split-action-target="rowsContainer" class="flex flex-col gap-1.5">
+ <% config["splits"].each_with_index do |split, idx| %>
+ <%= render "rule/actions/split_row", form: form, idx: idx, split: split, categories: categories, merchants: merchants, tags: tags %>
+ <% end %>
+ </div>
+
+ <div class="flex items-center justify-between gap-2">
+ <%= render DS::Button.new(
+ text: t("rules.actions.split.add_split"),
+ icon: "plus",
+ variant: "ghost",
+ size: :sm,
+ type: "button",
+ data: { action: "click->rule--split-action#addRow" }
+ ) %>
+
+ <span class="text-xs" data-rule--split-action-target="summary"></span>
+ </div>
+
+ <template data-rule--split-action-target="rowTemplate">
+ <%# Deliberately NOT "ROW_IDX_PLACEHOLDER": this template lives inside the action template
+ that rules_controller.js#addAction() clones for a new action, replacing every
+ occurrence of "IDX_PLACEHOLDER" with the new action's index — including inside the
+ substring "ROW_IDX_PLACEHOLDER", which corrupted this row placeholder into a
+ non-numeric key that Rails silently strips from split_rows params. %>
+ <%= render "rule/actions/split_row", form: form, idx: "SPLIT_ROW_PLACEHOLDER", split: { "type" => "percentage" }, categories: categories, merchants: merchants, tags: tags %>
+ </template>
+</div>
diff --git a/app/views/rule/actions/_split_row.html.erb b/app/views/rule/actions/_split_row.html.erb
new file mode 100644
index 0000000000..e863753f6a
--- /dev/null
+++ b/app/views/rule/actions/_split_row.html.erb
@@ -0,0 +1,59 @@
+<%# locals: (form:, idx:, split: {}, categories:, merchants:, tags:) %>
+
+<%# Same styled builder (form-field wrappers) and DS::TagSelect as the rest of the rule form, so
+ the split fields match the action-type select next to them. %>
+<div class="p-2 rounded-md border border-secondary bg-container flex flex-col gap-2" data-rule--split-action-target="row">
+ <%= fields "#{form.object_name}[split_rows][#{idx}]", builder: StyledFormBuilder do |row| %>
+ <%= row.text_field :name,
+ value: split["name"],
+ placeholder: t("rules.actions.split.name_placeholder"),
+ autocomplete: "off",
+ aria: { label: t("rules.actions.split.name_placeholder") } %>
+
+ <div class="flex items-center gap-2">
+ <%= row.select :type,
+ [ [ t("rules.actions.split.type_fixed"), "fixed" ], [ t("rules.actions.split.type_percentage"), "percentage" ] ],
+ { selected: split["type"] == "fixed" ? "fixed" : "percentage", container_class: "flex-1 min-w-0" },
+ aria: { label: t("rules.actions.split.type_label") },
+ data: { rule__split_action_target: "typeSelect", action: "change->rule--split-action#updateSummary" } %>
+
+ <%= row.number_field :share,
+ value: split["share"],
+ step: "0.01",
+ min: "0",
+ placeholder: "0.00",
+ autocomplete: "off",
+ container_class: "w-28 shrink-0",
+ aria: { label: t("rules.actions.split.share_label") },
+ data: { rule__split_action_target: "shareInput", action: "input->rule--split-action#updateSummary" } %>
+
+ <%= icon(
+ "trash-2",
+ size: "sm",
+ as_button: true,
+ aria: { label: t("rules.actions.split.remove_split") },
+ data: { action: "rule--split-action#removeRow" }) %>
+ </div>
+
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
+ <%= row.select :category_id,
+ categories,
+ { selected: split["category_id"], include_blank: t("splits.new.uncategorized"), container_class: "min-w-0" },
+ aria: { label: t("rules.actions.split.category_label") } %>
+
+ <%= row.select :merchant_id,
+ merchants,
+ { selected: split["merchant_id"], include_blank: t("splits.new.no_merchant"), container_class: "min-w-0" },
+ aria: { label: t("rules.actions.split.merchant_label") } %>
+ </div>
+
+ <%= render DS::TagSelect.new(
+ form: row,
+ tags: tags,
+ selected_ids: Array(split["tag_ids"]),
+ label: t("rules.actions.split.tags_label"),
+ show_label: false,
+ compact: true
+ ) %>
+ <% end %>
+</div>
diff --git a/app/views/splits/_category_select.html.erb b/app/views/splits/_category_select.html.erb
deleted file mode 100644
index f9f81952df..0000000000
--- a/app/views/splits/_category_select.html.erb
+++ /dev/null
@@ -1,85 +0,0 @@
-<%# locals: (name:, categories:, selected_id: nil) %>
-<%
- selected_category = categories.find { |c| c.id == selected_id }
-%>
-
-<div class="category-select-container relative flex-1 md:flex-initial md:w-auto md:min-w-44 md:max-w-72" data-controller="select list-filter form-dropdown category-badge-select" data-action="dropdown:select->form-dropdown#onSelect dropdown:select->category-badge-select#updateButton">
- <label class="text-xs font-medium text-secondary uppercase tracking-wide block mb-1"><%= t("splits.new.category_label") %></label>
- <input type="hidden"
- name="<%= name %>"
- value="<%= selected_id %>"
- data-form-dropdown-target="input">
- <button type="button"
- class="form-field__input w-full overflow-hidden border border-secondary rounded-md pl-2.5 pr-7 py-1.5 text-sm text-primary bg-container"
- data-select-target="button"
- data-category-badge-select-target="button"
- data-action="click->select#toggle"
- aria-haspopup="listbox"
- aria-expanded="false">
- <% if selected_category %>
- <%# Same DS::Pill shape as the canonical categories/badge partial; rendered
- directly (without its div wrapper) because a button only allows
- phrasing content. category-badge-select clones the option's pill into
- this button on selection, so both must stay the same markup. %>
- <%= render DS::Pill.new(
- label: selected_category.display_name,
- custom_color: selected_category.color,
- icon: selected_category.lucide_icon.presence,
- icon_size: "sm",
- marker: false,
- size: :md,
- truncate: true,
- title: selected_category.display_name) %>
- <% else %>
- <%= t("splits.new.uncategorized") %>
- <% end %>
- </button>
- <div class="absolute z-50 p-1.5 w-full min-w-48 md:w-80 rounded-lg shadow-lg shadow-border-xs bg-container mt-1.5 transition duration-150 ease-out -translate-y-1 opacity-0 hidden" data-select-target="menu">
- <div class="flex items-center bg-container border border-secondary rounded-lg mb-1 focus-within:ring-4 focus-within:ring-alpha-black-200 theme-dark:focus-within:ring-alpha-white-300 transition-shadow">
- <%= render DS::SearchInput.new(
- variant: :embedded,
- placeholder: t("helpers.select.search_placeholder"),
- data: {
- list_filter_target: "input",
- action: "list-filter#filter"
- }
- ) %>
- </div>
- <div data-list-filter-target="list" data-select-target="content" class="flex flex-col gap-0.5 max-h-64 overflow-auto" role="listbox" tabindex="-1">
- <%# Uncategorized option %>
- <% is_blank_selected = selected_id.blank? %>
- <div class="filterable-item text-sm cursor-pointer flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-container-inset-hover <%= "bg-container-inset" if is_blank_selected %>"
- role="option"
- tabindex="0"
- aria-selected="<%= is_blank_selected %>"
- data-action="click->select#select"
- data-value=""
- data-filter-name="<%= t("splits.new.uncategorized") %>">
- <span class="check-icon <%= "hidden" unless is_blank_selected %>">
- <%= icon("check") %>
- </span>
- <%= t("splits.new.uncategorized") %>
- </div>
-
- <% categories.each do |category| %>
- <% is_child = category.parent_id.present? %>
- <% is_selected = category.id == selected_id %>
- <div class="filterable-item text-sm cursor-pointer flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-container-inset-hover <%= "bg-container-inset" if is_selected %>"
- role="option"
- tabindex="0"
- aria-selected="<%= is_selected %>"
- data-action="click->select#select"
- data-value="<%= category.id %>"
- data-filter-name="<%= category.display_name %>">
- <span class="check-icon <%= "hidden" unless is_selected %>">
- <%= icon("check") %>
- </span>
- <% if is_child %>
- <%= icon("corner-down-right", size: "sm") %>
- <% end %>
- <%= render partial: "categories/badge", locals: { category: category } %>
- </div>
- <% end %>
- </div>
- </div>
-</div>
diff --git a/app/views/splits/_row.html.erb b/app/views/splits/_row.html.erb
new file mode 100644
index 0000000000..d73fca1f32
--- /dev/null
+++ b/app/views/splits/_row.html.erb
@@ -0,0 +1,71 @@
+<%# locals: (index:, categories:, merchants:, tags:, name: nil, amount: nil, category_id: nil, merchant_id: nil, tag_ids: [], removable: true) %>
+
+<%# Styled builder fields and DS pickers, the same controls as the transaction form. %>
+<div class="p-3 rounded-lg border border-secondary bg-container space-y-2" data-split-transaction-target="row">
+ <%= fields "split[splits][#{index}]", builder: StyledFormBuilder do |row| %>
+ <div class="flex flex-wrap md:flex-nowrap items-center gap-2">
+ <%= row.text_field :name,
+ value: name,
+ label: t("splits.new.name_label"),
+ placeholder: t("splits.new.name_placeholder"),
+ required: true,
+ autocomplete: "off",
+ container_class: "w-full md:flex-1 min-w-0",
+ data: { split_transaction_target: "nameInput" } %>
+
+ <%= row.number_field :amount,
+ value: amount,
+ label: t("splits.new.amount_label"),
+ placeholder: "0.00",
+ step: "0.01",
+ required: true,
+ autocomplete: "off",
+ container_class: "flex-1 md:flex-none md:w-32",
+ data: { split_transaction_target: "amountInput", action: "input->split-transaction#updateRemaining" } %>
+
+ <% if removable %>
+ <%= icon "x",
+ size: "sm",
+ as_button: true,
+ aria: { label: t("splits.new.remove_row") },
+ data: { action: "click->split-transaction#removeRow" } %>
+ <% else %>
+ <div class="w-8 shrink-0 hidden md:block"></div>
+ <% end %>
+ </div>
+
+ <%# Category and merchant share a row and tags get their own, like in the rule form, so the
+ category badge has room for real category names. %>
+ <div class="grid grid-cols-1 md:grid-cols-2 items-start gap-2">
+ <div class="category-select-container min-w-0">
+ <%= row.collection_select :category_id,
+ categories,
+ :id,
+ :display_name,
+ { selected: category_id, include_blank: t("splits.new.uncategorized"), label: t("splits.new.category_label"),
+ variant: :badge, searchable: true, scoped_ids: true } %>
+ </div>
+
+ <div class="min-w-0">
+ <%= render DS::MerchantSelect.new(
+ form: row,
+ method: :merchant_id,
+ merchants: merchants,
+ selected_id: merchant_id,
+ label: t("splits.new.merchant_label"),
+ include_blank: t("splits.new.no_merchant")
+ ) %>
+ </div>
+
+ <div class="min-w-0 md:col-span-2">
+ <%= render DS::TagSelect.new(
+ form: row,
+ tags: tags,
+ selected_ids: Array(tag_ids),
+ label: t("splits.new.tags_label"),
+ compact: true
+ ) %>
+ </div>
+ </div>
+ <% end %>
+</div>
diff --git a/app/views/splits/edit.html.erb b/app/views/splits/edit.html.erb
index 5d272bee68..ebb87ee2fe 100644
--- a/app/views/splits/edit.html.erb
+++ b/app/views/splits/edit.html.erb
@@ -36,47 +36,27 @@
<%# Split rows pre-filled from existing children %>
<div data-split-transaction-target="rowsContainer" class="space-y-3">
<% @children.each_with_index do |child, index| %>
- <div class="p-3 rounded-lg border border-secondary bg-container" data-split-transaction-target="row">
- <div class="flex flex-wrap md:flex-nowrap items-end gap-2">
- <div class="w-full md:flex-1 md:w-auto min-w-0 md:min-w-28">
- <label class="text-xs font-medium text-secondary uppercase tracking-wide block mb-1"><%= t("splits.new.name_label") %></label>
- <input type="text"
- name="split[splits][<%= index %>][name]"
- placeholder="<%= t("splits.new.name_placeholder") %>"
- class="form-field__input border border-secondary rounded-md px-2.5 py-1.5 w-full text-sm text-primary bg-container"
- required
- autocomplete="off"
- value="<%= child.name %>"
- data-split-transaction-target="nameInput">
- </div>
- <div class="flex-1 md:flex-none md:w-28">
- <label class="text-xs font-medium text-secondary uppercase tracking-wide block mb-1"><%= t("splits.new.amount_label") %></label>
- <input type="number"
- name="split[splits][<%= index %>][amount]"
- placeholder="0.00"
- step="0.01"
- class="form-field__input border border-secondary rounded-md px-2.5 py-1.5 w-full text-sm text-primary bg-container"
- required
- autocomplete="off"
- value="<%= (-child.amount).to_f %>"
- data-split-transaction-target="amountInput"
- data-action="input->split-transaction#updateRemaining">
- </div>
- <%= render "splits/category_select",
- name: "split[splits][#{index}][category_id]",
- categories: @categories,
- selected_id: child.entryable.try(:category_id) %>
- <button type="button"
- class="w-8 h-8 shrink-0 flex items-center justify-center rounded-md text-secondary hover:text-primary hover:bg-surface-hover transition-colors"
- aria-label="<%= t("splits.new.remove_row") %>"
- data-action="click->split-transaction#removeRow">
- <%= icon "x", size: "sm" %>
- </button>
- </div>
- </div>
+ <%= render "splits/row",
+ index: index,
+ name: child.name,
+ amount: (-child.amount).to_f,
+ category_id: child.entryable.try(:category_id),
+ merchant_id: child.entryable.try(:merchant_id),
+ tag_ids: child.entryable.try(:tag_ids) || [],
+ categories: @categories,
+ merchants: @merchants,
+ tags: @tags %>
<% end %>
</div>
+ <template data-split-transaction-target="rowTemplate">
+ <%= render "splits/row",
+ index: "ROW_IDX_PLACEHOLDER",
+ categories: @categories,
+ merchants: @merchants,
+ tags: @tags %>
+ </template>
+
<%# Add split button %>
<button type="button"
class="flex items-center justify-center gap-1.5 w-full py-2 text-sm font-medium text-secondary hover:text-primary border border-dashed border-secondary hover:border-primary rounded-lg transition-colors"
diff --git a/app/views/splits/new.html.erb b/app/views/splits/new.html.erb
index 74063ca3ca..38a59c9a06 100644
--- a/app/views/splits/new.html.erb
+++ b/app/views/splits/new.html.erb
@@ -34,40 +34,23 @@
<%# Split rows %>
<div data-split-transaction-target="rowsContainer" class="space-y-3">
- <div class="p-3 rounded-lg border border-secondary bg-container" data-split-transaction-target="row">
- <div class="flex flex-wrap md:flex-nowrap items-end gap-2">
- <div class="w-full md:flex-1 md:w-auto min-w-0 md:min-w-28">
- <label class="text-xs font-medium text-secondary uppercase tracking-wide block mb-1"><%= t("splits.new.name_label") %></label>
- <input type="text"
- name="split[splits][0][name]"
- placeholder="<%= t("splits.new.name_placeholder") %>"
- class="form-field__input border border-secondary rounded-md px-2.5 py-1.5 w-full text-sm text-primary bg-container"
- required
- autocomplete="off"
- value="<%= @entry.name %>"
- data-split-transaction-target="nameInput">
- </div>
- <div class="flex-1 md:flex-none md:w-28">
- <label class="text-xs font-medium text-secondary uppercase tracking-wide block mb-1"><%= t("splits.new.amount_label") %></label>
- <input type="number"
- name="split[splits][0][amount]"
- placeholder="0.00"
- step="0.01"
- class="form-field__input border border-secondary rounded-md px-2.5 py-1.5 w-full text-sm text-primary bg-container"
- required
- autocomplete="off"
- data-split-transaction-target="amountInput"
- data-action="input->split-transaction#updateRemaining">
- </div>
- <%= render "splits/category_select",
- name: "split[splits][0][category_id]",
- categories: @categories,
- selected_id: nil %>
- <div class="w-8 shrink-0 hidden md:block"></div>
- </div>
- </div>
+ <%= render "splits/row",
+ index: 0,
+ name: @entry.name,
+ categories: @categories,
+ merchants: @merchants,
+ tags: @tags,
+ removable: false %>
</div>
+ <template data-split-transaction-target="rowTemplate">
+ <%= render "splits/row",
+ index: "ROW_IDX_PLACEHOLDER",
+ categories: @categories,
+ merchants: @merchants,
+ tags: @tags %>
+ </template>
+
<%# Add split button %>
<button type="button"
class="flex items-center justify-center gap-1.5 w-full py-2 text-sm font-medium text-secondary hover:text-primary border border-dashed border-secondary hover:border-primary rounded-lg transition-colors"
diff --git a/config/locales/models/rule/de.yml b/config/locales/models/rule/de.yml
index c4acd46044..00d148bb78 100644
--- a/config/locales/models/rule/de.yml
+++ b/config/locales/models/rule/de.yml
@@ -7,6 +7,23 @@ de:
duplicate_actions: 'Eine Regel darf keine doppelten Aktionen enthalten: %{types}'
min_actions: braucht mindestens eine Aktion
nested_conditions: Zusammengesetzte Bedingungen lassen sich nicht verschachteln
+ split_not_alone: Eine Regel mit Aufteilung darf keine weiteren Aktionen haben
+ rule/action:
+ attributes:
+ value:
+ invalid_config: "muss eine gültige Split-Konfiguration sein"
+ invalid_split_count: "muss zwischen %{min} und %{max} Splits enthalten"
+ split_name_required: "Split #%{index} hat keinen Namen"
+ split_name_too_long: "Split #%{index}: Name ist zu lang (max. 255 Zeichen)"
+ split_name_invalid: "Split #%{index}: Name enthält ungültige Zeichen"
+ split_type_invalid: "Split #%{index}: Typ muss „fixed“ oder „percentage“ sein"
+ split_share_invalid: "Split #%{index}: Anteil muss eine positive Zahl sein"
+ split_category_invalid: "Split #%{index}: Kategorie gehört nicht zu dieser Familie"
+ split_merchant_invalid: "Split #%{index}: Händler gehört nicht zu dieser Familie"
+ split_tags_invalid: "Split #%{index}: enthält einen Tag, der nicht zu dieser Familie gehört"
+ percentages_must_total_100: "Prozentwerte müssen in Summe 100 ergeben (aktuell %{total})"
+ fixed_requires_exact_amount_condition: "Splits mit festen Beträgen benötigen eine Regel-Bedingung mit exaktem Transaktionsbetrag (z. B. Betrag = 42,00), sonst können die Anteile nicht zuverlässig für jede passende Transaktion aufgehen"
+ fixed_shares_must_equal_condition_amount: "Die Split-Anteile müssen in Summe %{amount} ergeben – den exakten Betrag, den die Bedingung dieser Regel vorgibt"
rule:
conditions:
unsupported_label: "Nicht unterstützt (%{type})"
diff --git a/config/locales/models/rule/en.yml b/config/locales/models/rule/en.yml
index 716b652635..30432251f6 100644
--- a/config/locales/models/rule/en.yml
+++ b/config/locales/models/rule/en.yml
@@ -7,6 +7,24 @@ en:
min_actions: "must have at least one action"
duplicate_actions: "Rule cannot have duplicate actions %{types}"
nested_conditions: "Compound conditions cannot be nested"
+ split_not_alone: "A split rule cannot have other actions"
+ rule/action:
+ attributes:
+ value:
+ invalid_config: "must be a valid split configuration"
+ invalid_split_count: "must have between %{min} and %{max} splits"
+ split_name_required: "split #%{index} is missing a name"
+ split_name_too_long: "split #%{index} name is too long (max 255 characters)"
+ split_name_invalid: "split #%{index} name contains invalid characters"
+ split_type_invalid: "split #%{index} type must be fixed or percentage"
+ split_share_invalid: "split #%{index} share must be a positive number"
+ split_category_invalid: "split #%{index} category does not belong to this family"
+ split_merchant_invalid: "split #%{index} merchant does not belong to this family"
+ split_tags_invalid: "split #%{index} has a tag that does not belong to this family"
+ percentages_must_total_100: "percentages must add up to 100 (got %{total})"
+ fixed_requires_exact_amount_condition: "fixed-amount splits require a rule condition that matches an exact transaction amount (e.g. Amount = 42.00), otherwise the shares can't reliably sum to every matching transaction's total"
+ fixed_shares_must_equal_condition_amount: "split shares must add up to %{amount}, the exact amount required by this rule's condition"
+
rule/condition:
attributes:
value:
diff --git a/config/locales/views/rules/de.yml b/config/locales/views/rules/de.yml
index 4339c2279b..e42c5b1055 100644
--- a/config/locales/views/rules/de.yml
+++ b/config/locales/views/rules/de.yml
@@ -5,6 +5,22 @@ de:
no_condition: Keine Bedingung
actions:
value_placeholder: Wert eingeben
+ split:
+ type_fixed: Fester Betrag
+ type_percentage: Prozent
+ type_label: Split-Typ
+ add_split: Split hinzufügen
+ name_placeholder: Name des Splits
+ share_label: Betrag oder Prozentsatz des Splits
+ category_label: Kategorie des Splits
+ merchant_label: Händler des Splits
+ tags_label: "Tags des Splits"
+ remove_split: "Split entfernen"
+ hint: "Feste Beträge werden zuerst als exakte Summen abgezogen. Prozent-Splits verteilen anschließend den verbleibenden Betrag. Wenn hier ausschließlich feste Beträge verwendet werden, füge zusätzlich eine Bedingung mit einem exakten Transaktionsbetrag hinzu (z. B. Betrag = 42,00), da jede passende Transaktion denselben Gesamtbetrag haben muss, damit die festen Beträge aufgehen. Eine Regel mit Aufteilung darf keine weiteren Aktionen haben."
+ fixed_summary_label: fest
+ summary:
+ one: "%{count} Split"
+ other: "%{count} Splits"
apply_all:
button: Alle anwenden
confirm_title: Alle Regeln anwenden
diff --git a/config/locales/views/rules/en.yml b/config/locales/views/rules/en.yml
index 9c689cc344..9774bbfb0f 100644
--- a/config/locales/views/rules/en.yml
+++ b/config/locales/views/rules/en.yml
@@ -67,6 +67,22 @@ en:
actions:
to_label: to
value_placeholder: Enter a value
+ split:
+ type_fixed: Fixed amount
+ type_percentage: Percentage
+ type_label: Split type
+ add_split: Add split
+ name_placeholder: Split name
+ share_label: Split amount or percentage
+ category_label: Split category
+ merchant_label: Split merchant
+ tags_label: "Split tags"
+ remove_split: "Remove split"
+ hint: "Fixed splits are subtracted first, as exact amounts. Percentage splits then divide whatever's left. If every split here uses a fixed amount, also add a condition that matches an exact transaction amount (e.g. Amount = 42.00), since every matching transaction needs the same total for the fixed amounts to add up. A split rule can't have other actions."
+ fixed_summary_label: fixed
+ summary:
+ one: "%{count} split"
+ other: "%{count} splits"
update:
success: Rule updated
destroy:
diff --git a/config/locales/views/splits/de.yml b/config/locales/views/splits/de.yml
index 25e322cc45..2ab64c8f84 100644
--- a/config/locales/views/splits/de.yml
+++ b/config/locales/views/splits/de.yml
@@ -15,6 +15,9 @@ de:
amount_label: Betrag
category_label: Kategorie
uncategorized: "(nicht kategorisiert)"
+ merchant_label: Händler
+ no_merchant: "(Händler der Hauptbuchung)"
+ tags_label: Tags
original_name: "Name:"
original_date: "Datum:"
original_amount: "Betrag"
diff --git a/config/locales/views/splits/en.yml b/config/locales/views/splits/en.yml
index db9a5e037a..c7c2d0da3e 100644
--- a/config/locales/views/splits/en.yml
+++ b/config/locales/views/splits/en.yml
@@ -15,6 +15,9 @@ en:
amount_label: Amount
category_label: Category
uncategorized: "(uncategorized)"
+ merchant_label: Merchant
+ no_merchant: "(transaction's merchant)"
+ tags_label: Tags
original_name: "Name:"
original_date: "Date:"
original_amount: "Amount"
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index b461549edf..f3735da843 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -62,6 +62,16 @@ components:
category_id:
type: string
nullable: true
+ merchant_id:
+ type: string
+ nullable: true
+ description: Omitted or null, the child takes the parent's merchant
+ tag_ids:
+ type: array
+ items:
+ type: string
+ nullable: true
+ description: No tags when omitted
excluded:
type: boolean
nullable: true
@@ -9262,7 +9272,9 @@ paths:
security:
- apiKeyAuth: []
description: Replaces the children of an existing split. The previous children
- are destroyed, so anything set on them afterwards is not carried over.
+ are destroyed, so anything set on them afterwards is not carried over. Send
+ each child in full, including its merchant_id and tag_ids. A child without
+ a merchant_id takes the parent's merchant.
parameters: []
responses:
'200':
diff --git a/spec/requests/api/v1/splits_spec.rb b/spec/requests/api/v1/splits_spec.rb
index dca430dec8..3921657644 100644
--- a/spec/requests/api/v1/splits_spec.rb
+++ b/spec/requests/api/v1/splits_spec.rb
@@ -118,7 +118,9 @@ RSpec.describe 'API V1 Transaction Split', type: :request do
tags 'Transactions'
security [ { apiKeyAuth: [] } ]
description 'Replaces the children of an existing split. The previous children are ' \
- 'destroyed, so anything set on them afterwards is not carried over.'
+ 'destroyed, so anything set on them afterwards is not carried over. Send ' \
+ 'each child in full, including its merchant_id and tag_ids. A child without a ' \
+ 'merchant_id takes the parent\'s merchant.'
consumes 'application/json'
produces 'application/json'
parameter name: :split, in: :body, schema: { '$ref' => '#/components/schemas/SplitRequest' }
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 4d41023500..71c692b9c5 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -72,6 +72,8 @@ RSpec.configure do |config|
name: { type: :string, nullable: true, description: 'Defaults to the parent name when omitted' },
amount: { type: :string, description: 'Same sign convention as the transaction amount' },
category_id: { type: :string, nullable: true },
+ merchant_id: { type: :string, nullable: true, description: "Omitted or null, the child takes the parent's merchant" },
+ tag_ids: { type: :array, items: { type: :string }, nullable: true, description: 'No tags when omitted' },
excluded: { type: :boolean, nullable: true }
}
}
diff --git a/test/controllers/api/v1/splits_controller_test.rb b/test/controllers/api/v1/splits_controller_test.rb
index 98b795a2b3..8834c522e8 100644
--- a/test/controllers/api/v1/splits_controller_test.rb
+++ b/test/controllers/api/v1/splits_controller_test.rb
@@ -347,6 +347,144 @@ class Api::V1::SplitsControllerTest < ActionDispatch::IntegrationTest
assert body["amount_cents"].is_a?(Integer)
end
+ # Merchants and tags per child
+
+ test "assigns merchants and tags to children" do
+ merchant = merchants(:amazon)
+ tag = tags(:one)
+ params = { split: { splits: [
+ { name: "Tagged", amount: (@entry.amount / 2).to_s, merchant_id: merchant.id, tag_ids: [ tag.id ] },
+ { name: "Plain", amount: (@entry.amount / 2).to_s }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :created
+
+ tagged = JSON.parse(response.body)["children"].find { |c| c["name"] == "Tagged" }
+ assert_equal merchant.id, tagged.dig("merchant", "id")
+ assert_equal [ tag.id ], tagged["tags"].map { |t| t["id"] }
+
+ plain = @entry.reload.child_entries.find_by(name: "Plain").entryable
+ assert_empty plain.tags
+ end
+
+ test "omitting merchant_id keeps the parent's merchant on the child" do
+ @transaction.update!(merchant: merchants(:netflix))
+
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ assert_response :created
+ assert_equal [ merchants(:netflix).id ] * 2, @entry.reload.child_entries.map { |c| c.entryable.merchant_id }
+ end
+
+ test "a split read back and re-sent keeps each child's merchant and tags" do
+ # Splits made in the web dialog or by a split rule can carry their own merchant and tags.
+ @entry.split!([
+ { name: "Books", amount: @entry.amount / 2, merchant_id: merchants(:amazon).id, tag_ids: [ tags(:one).id, tags(:two).id ] },
+ { name: "Rest", amount: @entry.amount / 2 }
+ ])
+
+ get api_v1_transaction_split_url(@transaction), headers: api_headers(@api_key)
+ assert_response :success
+ children = JSON.parse(response.body)["children"]
+
+ resent = children.map do |c|
+ { name: c["name"], amount: c["amount_decimal"], excluded: c["excluded"],
+ merchant_id: c.dig("merchant", "id"), tag_ids: c["tags"].map { |t| t["id"] } }
+ end
+ patch api_v1_transaction_split_url(@transaction), params: { split: { splits: resent } },
+ headers: api_headers(@api_key), as: :json
+ assert_response :success
+
+ books = @entry.reload.child_entries.find_by(name: "Books").entryable
+ assert_equal merchants(:amazon).id, books.merchant_id
+ assert_equal [ tags(:one).id, tags(:two).id ].sort, books.tag_ids.sort
+ end
+
+ test "rejects a merchant from another family" do
+ other_family = Family.create!(name: "Other", currency: "USD", locale: "en", date_format: "%m-%d-%Y")
+ foreign = FamilyMerchant.create!(family: other_family, name: "Foreign shop", color: "#000000")
+ params = { split: { splits: [
+ { name: "A", amount: (@entry.amount / 2).to_s, merchant_id: foreign.id },
+ { name: "B", amount: (@entry.amount / 2).to_s }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "rejects a tag belonging to another family" do
+ other_family = Family.create!(name: "Other", currency: "USD", locale: "en", date_format: "%m-%d-%Y")
+ foreign = other_family.tags.create!(name: "Foreign")
+ params = { split: { splits: [
+ { name: "A", amount: (@entry.amount / 2).to_s, tag_ids: [ tags(:one).id, foreign.id ] },
+ { name: "B", amount: (@entry.amount / 2).to_s }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "rejects a foreign merchant when replacing a split" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ before = @entry.reload.child_entries.order(:id).pluck(:id)
+
+ other_family = Family.create!(name: "Other", currency: "USD", locale: "en", date_format: "%m-%d-%Y")
+ foreign = FamilyMerchant.create!(family: other_family, name: "Foreign shop", color: "#000000")
+ params = halves
+ params[:split][:splits][0][:merchant_id] = foreign.id
+
+ patch api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ assert_equal before, @entry.reload.child_entries.order(:id).pluck(:id)
+ end
+
+ test "rejects a provider merchant the user has no transaction with" do
+ stranger = ProviderMerchant.create!(name: "Unseen Shop", source: "plaid", provider_merchant_id: "api-split-unseen")
+ params = halves
+ params[:split][:splits][0][:merchant_id] = stranger.id
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "returns 422 when a category or merchant id is not a string" do
+ [ { category_id: [ @family.categories.first.id ] }, { merchant_id: { id: merchants(:amazon).id } }, { merchant_id: 1 } ].each do |bad|
+ params = halves
+ params[:split][:splits][0].merge!(bad)
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity, bad.inspect
+ end
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "returns 422 when tag_ids is not an array of ids" do
+ [ tags(:one).id, [ { id: tags(:one).id } ], { id: tags(:one).id } ].each do |tag_ids|
+ params = { split: { splits: [
+ { name: "A", amount: (@entry.amount / 2).to_s, tag_ids: tag_ids },
+ { name: "B", amount: (@entry.amount / 2).to_s }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity, "tag_ids: #{tag_ids.inspect}"
+ end
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "names the current reason when the transaction stops being splittable under the lock" do
+ # A provider sync marked the transaction pending after the controller's own splittable? check
+ # passed (stubbed here); split_once! sees it under the lock.
+ Transaction.where(id: @transaction.id).update_all(extra: { "plaid" => { "pending" => true } })
+ Transaction.any_instance.stubs(:splittable?).returns(true)
+
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ assert_equal [ "Transaction is pending" ], JSON.parse(response.body)["errors"]
+ end
+
test "returns 401 without an API key" do
get api_v1_transaction_split_url(@transaction)
assert_response :unauthorized
diff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rb
index 1c2a7009b7..2d6858bc77 100644
--- a/test/controllers/rules_controller_test.rb
+++ b/test/controllers/rules_controller_test.rb
@@ -92,141 +92,79 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to confirm_rule_url(rule, reload_on_close: true)
end
- test "rejects a null byte in a condition instead of returning a server error" do
- assert_no_difference "Rule.count" do
- post rules_url, params: {
- rule: {
- resource_type: "transaction",
- conditions_attributes: {
- "0" => { condition_type: "transaction_name", operator: "like", value: "cof\0fee" }
- },
- actions_attributes: {
- "0" => { action_type: "exclude_transaction" }
- }
- }
- }
- end
-
- assert_response :unprocessable_entity
- assert_select "p.text-destructive", text: /Conditions value is invalid/
- end
-
- test "rejects a null byte when updating an action" do
- rule = rules(:one)
- action = rule.actions.first
-
- patch rule_url(rule), params: {
- rule: {
- actions_attributes: {
- "0" => { id: action.id, action_type: "set_transaction_name", value: "bad\0value" }
- }
- }
- }
-
- assert_response :unprocessable_entity
- assert_equal action.value, action.reload.value
- end
-
- test "rejects a null byte in the condition operator" do
- assert_no_difference "Rule.count" do
- post rules_url, params: {
- rule: {
- resource_type: "transaction",
- conditions_attributes: {
- "0" => { condition_type: "transaction_name", operator: "like\0", value: "coffee" }
- },
- actions_attributes: { "0" => { action_type: "exclude_transaction" } }
- }
- }
- end
-
- assert_response :unprocessable_entity
- assert_equal "text/plain", response.media_type
- assert_match(/operator is invalid/i, response.body)
- end
-
- test "rejects a null byte in a nested condition operator" do
- assert_no_difference "Rule.count" do
- post rules_url, params: {
- rule: {
- resource_type: "transaction",
- conditions_attributes: {
- "0" => {
- condition_type: "compound", operator: "and",
- sub_conditions_attributes: {
- "0" => { condition_type: "transaction_name", operator: "like\0", value: "coffee" }
- }
- }
- },
- actions_attributes: { "0" => { action_type: "exclude_transaction" } }
- }
- }
- end
-
- assert_response :unprocessable_entity
- assert_equal "text/plain", response.media_type
- assert_match(/operator is invalid/i, response.body)
- end
+ test "creates rule with a split_transaction action from split_rows params" do
+ category = categories(:food_and_drink)
- test "rejects a null byte in the condition type without selecting a different type" do
post rules_url, params: {
rule: {
+ effective_date: 30.days.ago.to_date,
resource_type: "transaction",
conditions_attributes: {
- "0" => { condition_type: "transaction_name\0", operator: "like", value: "coffee" }
+ "0" => {
+ condition_type: "transaction_name",
+ operator: "like",
+ value: "Netflix+Hulu Bundle"
+ }
},
- actions_attributes: { "0" => { action_type: "exclude_transaction" } }
- }
- }
-
- assert_response :unprocessable_entity
- assert_equal "text/plain", response.media_type
- assert_match(/condition type is invalid/i, response.body)
- end
-
- test "rejects a null byte in the action type without failing to render" do
- assert_no_difference "Rule.count" do
- post rules_url, params: {
- rule: {
- resource_type: "transaction",
- actions_attributes: { "0" => { action_type: "exclude_transaction\0" } }
+ actions_attributes: {
+ "0" => {
+ action_type: "split_transaction",
+ split_rows: {
+ "0" => { type: "percentage", name: "Netflix", share: "70", category_id: category.id },
+ "1" => { type: "percentage", name: "Hulu", share: "30", category_id: "" }
+ }
+ }
}
}
- end
+ }
- assert_response :unprocessable_entity
- assert_equal "text/plain", response.media_type
- assert_match(/action type is invalid/i, response.body)
- end
+ rule = @user.family.rules.order("created_at DESC").first
- test "rejects a null byte when updating the action type" do
- rule = rules(:one)
+ assert_equal 1, rule.actions.count
action = rule.actions.first
- original_type = action.action_type
+ assert_equal "split_transaction", action.action_type
- patch rule_url(rule), params: {
- rule: { actions_attributes: { "0" => { id: action.id, action_type: "#{original_type}\0" } } }
- }
+ parsed_value = JSON.parse(action.value)
+ assert_equal [ "Netflix", "Hulu" ], parsed_value["splits"].map { |s| s["name"] }
+ assert_equal [ "percentage", "percentage" ], parsed_value["splits"].map { |s| s["type"] }
+ assert_equal category.id, parsed_value["splits"].first["category_id"]
+ assert_nil parsed_value["splits"].last["category_id"]
- assert_response :unprocessable_entity
- assert_equal "text/plain", response.media_type
- assert_match(/action type is invalid/i, response.body)
- assert_equal original_type, action.reload.action_type
+ assert_redirected_to confirm_rule_url(rule, reload_on_close: true)
end
- test "rejects a null byte in the resource type without failing to render" do
- assert_no_difference "Rule.count" do
- post rules_url, params: {
- rule: {
- resource_type: "transaction\0",
- actions_attributes: { "0" => { action_type: "exclude_transaction" } }
+ test "updates the split rows of an existing split_transaction action" do
+ rule = @user.family.rules.create!(
+ name: "Existing split",
+ resource_type: "transaction",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "rent") ],
+ actions: [
+ Rule::Action.new(
+ action_type: "split_transaction",
+ value: { splits: [ { type: "percentage", name: "A", share: "50" }, { type: "percentage", name: "B", share: "50" } ] }.to_json
+ )
+ ]
+ )
+ action = rule.actions.sole
+
+ patch rule_url(rule), params: {
+ rule: {
+ actions_attributes: {
+ "0" => {
+ id: action.id,
+ action_type: "split_transaction",
+ split_rows: {
+ "0" => { type: "percentage", name: "A", share: "60", category_id: categories(:food_and_drink).id },
+ "1" => { type: "percentage", name: "B", share: "40", category_id: "" }
+ }
+ }
}
}
- end
+ }
- assert_response :unprocessable_entity
- assert_equal "text/plain", response.media_type
- assert_match(/resource type is invalid/i, response.body)
+ splits = JSON.parse(action.reload.value)["splits"]
+ assert_equal [ "60", "40" ], splits.map { |split| split["share"] }
+ assert_equal categories(:food_and_drink).id, splits.first["category_id"]
end
test "rejects unknown action and resource types on create without saving or failing to render" do
@@ -710,6 +648,143 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
assert_equal "connection refused", entry.metadata["error_message"]
end
+ test "rejects a null byte in a condition instead of returning a server error" do
+ assert_no_difference "Rule.count" do
+ post rules_url, params: {
+ rule: {
+ resource_type: "transaction",
+ conditions_attributes: {
+ "0" => { condition_type: "transaction_name", operator: "like", value: "cof\0fee" }
+ },
+ actions_attributes: {
+ "0" => { action_type: "exclude_transaction" }
+ }
+ }
+ }
+ end
+
+ assert_response :unprocessable_entity
+ assert_select "p.text-destructive", text: /Conditions value is invalid/
+ end
+
+ test "rejects a null byte when updating an action" do
+ rule = rules(:one)
+ action = rule.actions.first
+
+ patch rule_url(rule), params: {
+ rule: {
+ actions_attributes: {
+ "0" => { id: action.id, action_type: "set_transaction_name", value: "bad\0value" }
+ }
+ }
+ }
+
+ assert_response :unprocessable_entity
+ assert_equal action.value, action.reload.value
+ end
+
+ test "rejects a null byte in the condition operator" do
+ assert_no_difference "Rule.count" do
+ post rules_url, params: {
+ rule: {
+ resource_type: "transaction",
+ conditions_attributes: {
+ "0" => { condition_type: "transaction_name", operator: "like\0", value: "coffee" }
+ },
+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }
+ }
+ }
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal "text/plain", response.media_type
+ assert_match(/operator is invalid/i, response.body)
+ end
+
+ test "rejects a null byte in a nested condition operator" do
+ assert_no_difference "Rule.count" do
+ post rules_url, params: {
+ rule: {
+ resource_type: "transaction",
+ conditions_attributes: {
+ "0" => {
+ condition_type: "compound", operator: "and",
+ sub_conditions_attributes: {
+ "0" => { condition_type: "transaction_name", operator: "like\0", value: "coffee" }
+ }
+ }
+ },
+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }
+ }
+ }
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal "text/plain", response.media_type
+ assert_match(/operator is invalid/i, response.body)
+ end
+
+ test "rejects a null byte in the condition type without selecting a different type" do
+ post rules_url, params: {
+ rule: {
+ resource_type: "transaction",
+ conditions_attributes: {
+ "0" => { condition_type: "transaction_name\0", operator: "like", value: "coffee" }
+ },
+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }
+ }
+ }
+
+ assert_response :unprocessable_entity
+ assert_equal "text/plain", response.media_type
+ assert_match(/condition type is invalid/i, response.body)
+ end
+
+ test "rejects a null byte in the action type without failing to render" do
+ assert_no_difference "Rule.count" do
+ post rules_url, params: {
+ rule: {
+ resource_type: "transaction",
+ actions_attributes: { "0" => { action_type: "exclude_transaction\0" } }
+ }
+ }
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal "text/plain", response.media_type
+ assert_match(/action type is invalid/i, response.body)
+ end
+
+ test "rejects a null byte when updating the action type" do
+ rule = rules(:one)
+ action = rule.actions.first
+ original_type = action.action_type
+
+ patch rule_url(rule), params: {
+ rule: { actions_attributes: { "0" => { id: action.id, action_type: "#{original_type}\0" } } }
+ }
+
+ assert_response :unprocessable_entity
+ assert_equal "text/plain", response.media_type
+ assert_match(/action type is invalid/i, response.body)
+ assert_equal original_type, action.reload.action_type
+ end
+
+ test "rejects a null byte in the resource type without failing to render" do
+ assert_no_difference "Rule.count" do
+ post rules_url, params: {
+ rule: {
+ resource_type: "transaction\0",
+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }
+ }
+ }
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal "text/plain", response.media_type
+ assert_match(/resource type is invalid/i, response.body)
+ end
+
# The edit form resubmits every condition and action id with its current
# values, so these tests submit exactly what the rendered form holds (read back
# from the edit page) rather than a hand-picked subset.
diff --git a/test/controllers/splits_controller_test.rb b/test/controllers/splits_controller_test.rb
index 412ef7aef6..b639047236 100644
--- a/test/controllers/splits_controller_test.rb
+++ b/test/controllers/splits_controller_test.rb
@@ -32,6 +32,25 @@ class SplitsControllerTest < ActionDispatch::IntegrationTest
assert_equal parent_index + 1, child_index
end
+ test "new gives each split row's pickers their own ids and labelled controls" do
+ get new_transaction_split_path(@entry)
+ assert_response :success
+
+ doc = Nokogiri::HTML::Document.parse(response.body)
+ ids = doc.css("[data-split-transaction-target='row'] [id]").map { |node| node["id"] }
+ assert_empty ids.tally.select { |_id, count| count > 1 }.keys
+
+ trigger = doc.at_css("#split_splits_0_category_id_trigger")
+ assert_not_nil trigger
+ assert_equal "split_splits_0_category_id_label split_splits_0_category_id_trigger", trigger["aria-labelledby"]
+
+ %w[merchant_id tag_ids].each do |field|
+ label = doc.at_css("label[for='split_splits_0_#{field}']")
+ assert_not_nil label, "missing label for #{field}"
+ assert_equal "button", doc.at_css("#split_splits_0_#{field}")&.name
+ end
+ end
+
test "create with valid params splits transaction" do
assert_difference "Entry.count", 2 do
post transaction_split_path(@entry), params: {
@@ -155,6 +174,48 @@ class SplitsControllerTest < ActionDispatch::IntegrationTest
assert children.last.excluded?
end
+ test "create with merchant and tags sets them on children" do
+ assert_difference "Entry.count", 2 do
+ post transaction_split_path(@entry), params: {
+ split: {
+ splits: [
+ { name: "Groceries", amount: "-70", category_id: "", merchant_id: merchants(:amazon).id, tag_ids: [ tags(:one).id, tags(:two).id ] },
+ { name: "Household", amount: "-30", category_id: "" }
+ ]
+ }
+ }
+ end
+
+ children = @entry.child_entries.order(:amount)
+ groceries = children.find { |c| c.name == "Groceries" }
+ household = children.find { |c| c.name == "Household" }
+
+ assert_equal merchants(:amazon).id, groceries.entryable.merchant_id
+ assert_equal [ tags(:one), tags(:two) ].sort_by(&:id), groceries.entryable.tags.sort_by(&:id)
+ assert_nil household.entryable.merchant_id
+ end
+
+ test "create ignores merchant and tags belonging to another family" do
+ other_family = families(:empty)
+ foreign_merchant = other_family.merchants.create!(name: "Foreign merchant", type: "FamilyMerchant")
+ foreign_tag = other_family.tags.create!(name: "Foreign tag")
+
+ assert_difference "Entry.count", 2 do
+ post transaction_split_path(@entry), params: {
+ split: {
+ splits: [
+ { name: "Groceries", amount: "-70", category_id: "", merchant_id: foreign_merchant.id, tag_ids: [ foreign_tag.id ] },
+ { name: "Household", amount: "-30", category_id: "" }
+ ]
+ }
+ }
+ end
+
+ groceries = @entry.child_entries.order(:amount).find { |c| c.name == "Groceries" }
+ assert_nil groceries.entryable.merchant_id
+ assert_empty groceries.entryable.tags
+ end
+
# Edit action tests
test "edit renders with existing children pre-filled" do
@entry.split!([
@@ -249,6 +310,26 @@ class SplitsControllerTest < ActionDispatch::IntegrationTest
assert children.last.excluded?
end
+ test "update sets merchant and tags on children" do
+ @entry.split!([
+ { name: "Part 1", amount: 60, category_id: nil },
+ { name: "Part 2", amount: 40, category_id: nil }
+ ])
+
+ patch transaction_split_path(@entry), params: {
+ split: {
+ splits: [
+ { name: "Part 1", amount: "-60", category_id: "", merchant_id: merchants(:netflix).id, tag_ids: [ tags(:three).id ] },
+ { name: "Part 2", amount: "-40", category_id: "" }
+ ]
+ }
+ }
+
+ part_one = @entry.reload.child_entries.order(:amount).find { |c| c.name == "Part 1" }
+ assert_equal merchants(:netflix).id, part_one.entryable.merchant_id
+ assert_equal [ tags(:three) ], part_one.entryable.tags
+ end
+
# Destroy from child tests
test "destroy from child resolves to parent and unsplits" do
@entry.split!([
diff --git a/test/jobs/rule_job_test.rb b/test/jobs/rule_job_test.rb
index 6c761d1445..7109710591 100644
--- a/test/jobs/rule_job_test.rb
+++ b/test/jobs/rule_job_test.rb
@@ -52,6 +52,38 @@ class RuleJobTest < ActiveJob::TestCase
assert_equal 10, rule_run.transactions_blocked
end
+ test "captures a debug log entry when the rule run raises" do
+ rule = @family.rules.create!(
+ name: "Failing rule",
+ resource_type: "transaction",
+ effective_date: 1.year.ago.to_date,
+ conditions: [
+ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods")
+ ],
+ actions: [
+ Rule::Action.new(action_type: "set_transaction_category", value: @food_and_dining.id)
+ ]
+ )
+
+ error = RuntimeError.new("boom")
+ Rule.any_instance.stubs(:apply).raises(error)
+
+ assert_difference "DebugLogEntry.count", 1 do
+ assert_raises(RuntimeError) { RuleJob.perform_now(rule) }
+ end
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "rule_run", entry.category
+ assert_equal "error", entry.level
+ assert_equal "Rule::Runner", entry.source
+ assert_equal @family, entry.family
+ assert_equal rule.id, entry.metadata["rule_id"]
+ assert_equal "RuntimeError", entry.metadata["error_class"]
+
+ rule_run = rule.rule_runs.order(:created_at).last
+ assert_equal "failed", rule_run.status
+ end
+
test "a failing rule above is recorded but does not fail the job" do
create_transaction(account: @account, name: "Whole Foods")
above = @family.rules.create!(
diff --git a/test/models/assistant/function/create_rule_test.rb b/test/models/assistant/function/create_rule_test.rb
index 82b033ac27..1119d1bd98 100644
--- a/test/models/assistant/function/create_rule_test.rb
+++ b/test/models/assistant/function/create_rule_test.rb
@@ -38,6 +38,22 @@ class Assistant::Function::CreateRuleTest < ActiveSupport::TestCase
assert_equal 1, result[:preview][:match_count]
end
+ test "points split actions at the rules settings" do
+ split = { splits: [ { type: "percentage", name: "A", share: "50" }, { type: "percentage", name: "B", share: "50" } ] }
+
+ result = nil
+ assert_no_difference "@family.rules.count" do
+ result = @fn.call(
+ "name" => "Split",
+ "conditions" => [ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq" } ],
+ "actions" => [ { "action_type" => "split_transaction", "value" => split.to_json } ]
+ )
+ end
+
+ assert_not result[:success]
+ assert_match "add it in Settings > Rules", result[:problems].join
+ end
+
test "ignores an attempt to create an active rule" do
result = @fn.call(
"active" => true,
diff --git a/test/models/assistant/function/get_rule_options_test.rb b/test/models/assistant/function/get_rule_options_test.rb
index 0b4abecd35..f566403309 100644
--- a/test/models/assistant/function/get_rule_options_test.rb
+++ b/test/models/assistant/function/get_rule_options_test.rb
@@ -23,6 +23,7 @@ class Assistant::Function::GetRuleOptionsTest < ActiveSupport::TestCase
assert_includes action_types, "set_transaction_category"
assert_not_includes action_types, "auto_categorize"
assert_not_includes action_types, "auto_detect_merchants"
+ assert_not_includes action_types, "split_transaction"
end
test "inlines fixed value lists and points id values at their tools" do
diff --git a/test/models/entry/split_references_test.rb b/test/models/entry/split_references_test.rb
new file mode 100644
index 0000000000..5d4f6734cf
--- /dev/null
+++ b/test/models/entry/split_references_test.rb
@@ -0,0 +1,60 @@
+require "test_helper"
+
+class Entry::SplitReferencesTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @other_family = families(:empty)
+ end
+
+ test "keeps the family's own ids" do
+ references = Entry::SplitReferences.new(@family)
+
+ scoped = references.scope(
+ category_id: categories(:food_and_drink).id,
+ merchant_id: merchants(:netflix).id,
+ tag_ids: [ tags(:one).id, "", tags(:one).id ]
+ )
+
+ assert_equal categories(:food_and_drink).id, scoped[:category_id]
+ assert_equal merchants(:netflix).id, scoped[:merchant_id]
+ assert_equal [ tags(:one).id ], scoped[:tag_ids]
+ end
+
+ test "drops foreign and unknown ids" do
+ foreign_category = @other_family.categories.create!(name: "Foreign", color: "#000000")
+ foreign_merchant = @other_family.merchants.create!(name: "Foreign Shop")
+ foreign_tag = @other_family.tags.create!(name: "Foreign")
+
+ scoped = Entry::SplitReferences.new(@family).scope(
+ category_id: foreign_category.id,
+ merchant_id: foreign_merchant.id,
+ tag_ids: [ foreign_tag.id, SecureRandom.uuid ]
+ )
+
+ assert_equal({ category_id: nil, merchant_id: nil, tag_ids: [] }, scoped)
+ end
+
+ test "uses the given merchant scope instead of family merchants" do
+ provider_merchant = ProviderMerchant.create!(name: "Provider Shop", source: "plaid", provider_merchant_id: "split-ref-1")
+
+ family_only = Entry::SplitReferences.new(@family)
+ with_provider = Entry::SplitReferences.new(@family, merchants: Merchant.where(id: provider_merchant.id))
+
+ assert_nil family_only.scope(category_id: nil, merchant_id: provider_merchant.id, tag_ids: nil)[:merchant_id]
+ assert_equal provider_merchant.id, with_provider.scope(category_id: nil, merchant_id: provider_merchant.id, tag_ids: nil)[:merchant_id]
+ end
+
+ test "names the ids scope would drop" do
+ foreign_category = @other_family.categories.create!(name: "Foreign", color: "#000000")
+ foreign_merchant = @other_family.merchants.create!(name: "Foreign Shop")
+ missing_tag_id = SecureRandom.uuid
+ references = Entry::SplitReferences.new(@family)
+
+ assert_equal [ [ :category, foreign_category.id ], [ :merchant, foreign_merchant.id ], [ :tag, missing_tag_id ] ],
+ references.unknown(category_id: foreign_category.id, merchant_id: foreign_merchant.id,
+ tag_ids: [ tags(:one).id, missing_tag_id, "", missing_tag_id ])
+ assert_empty references.unknown(category_id: categories(:food_and_drink).id, merchant_id: merchants(:netflix).id,
+ tag_ids: [ tags(:one).id ])
+ assert_empty references.unknown(category_id: "", merchant_id: nil, tag_ids: nil)
+ end
+end
diff --git a/test/models/entry_split_test.rb b/test/models/entry_split_test.rb
index a7efa4d092..625e1d9d68 100644
--- a/test/models/entry_split_test.rb
+++ b/test/models/entry_split_test.rb
@@ -27,6 +27,59 @@ class EntrySplitTest < ActiveSupport::TestCase
assert @entry.split_parent?
end
+ test "split! locks only the fields a split sets when asked to" do
+ merchant = @entry.account.family.merchants.create!(name: "Lock merchant", type: "FamilyMerchant")
+ splits = [
+ { name: "Groceries", amount: 70, category_id: categories(:food_and_drink).id, merchant_id: merchant.id },
+ { name: "Household", amount: 30, category_id: nil }
+ ]
+
+ locked, unlocked = @entry.split!(splits, lock_attributes: true).map(&:transaction)
+
+ assert_equal %w[category_id merchant_id], locked.locked_attributes.keys.sort
+ assert_empty unlocked.locked_attributes
+ end
+
+ test "split! locks nothing by default" do
+ children = @entry.split!([
+ { name: "Groceries", amount: 70, category_id: categories(:food_and_drink).id },
+ { name: "Household", amount: 30, category_id: nil }
+ ])
+
+ assert children.all? { |child| child.transaction.locked_attributes.empty? }
+ end
+
+ test "split! supports a per-split merchant override, falling back to the parent's merchant" do
+ parent_merchant = @entry.account.family.merchants.create!(name: "Parent merchant", type: "FamilyMerchant")
+ split_merchant = @entry.account.family.merchants.create!(name: "Split merchant", type: "FamilyMerchant")
+ @entry.transaction.update!(merchant: parent_merchant)
+
+ splits = [
+ { name: "Groceries", amount: 70, merchant_id: split_merchant.id },
+ { name: "Household", amount: 30 }
+ ]
+
+ children = @entry.split!(splits)
+
+ assert_equal split_merchant.id, children.first.transaction.merchant_id
+ assert_equal parent_merchant.id, children.last.transaction.merchant_id
+ end
+
+ test "split! supports per-split tags" do
+ tag_one = @entry.account.family.tags.create!(name: "Tag one")
+ tag_two = @entry.account.family.tags.create!(name: "Tag two")
+
+ splits = [
+ { name: "Groceries", amount: 70, tag_ids: [ tag_one.id, tag_two.id ] },
+ { name: "Household", amount: 30 }
+ ]
+
+ children = @entry.split!(splits)
+
+ assert_equal [ tag_one, tag_two ].sort_by(&:id), children.first.transaction.tags.sort_by(&:id)
+ assert_equal [], children.last.transaction.tags
+ end
+
test "split! rejects when amounts don't sum to parent" do
splits = [
{ name: "Part 1", amount: 60, category_id: nil },
@@ -221,4 +274,70 @@ class EntrySplitTest < ActiveSupport::TestCase
assert_includes visible_entries.pluck(:id), non_excluded_child.id
refute_includes visible_entries.pluck(:id), excluded_child.id
end
+
+ test "split_once! splits an entry that is not yet split" do
+ assert @entry.split_once!([ { name: "A", amount: 60 }, { name: "B", amount: 40 } ])
+ assert_equal 2, @entry.reload.child_entries.count
+ end
+
+ test "split_once! skips an entry another caller split in the meantime" do
+ stale = Entry.find(@entry.id)
+ @entry.split!([ { name: "First", amount: 50 }, { name: "Run", amount: 50 } ])
+
+ assert_not stale.split_once!([ { name: "Second", amount: 100 } ])
+ assert_equal %w[First Run], @entry.reload.child_entries.order(:name).pluck(:name)
+ end
+
+ test "split_once! skips an entry excluded in the meantime" do
+ stale = Entry.find(@entry.id)
+ Entry.where(id: @entry.id).update_all(excluded: true)
+
+ assert_not stale.split_once!([ { name: "A", amount: 60 }, { name: "B", amount: 40 } ])
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "split_once! skips a transaction that became pending in the meantime" do
+ stale = Entry.find(@entry.id)
+ Transaction.where(id: @entry.entryable_id).update_all(extra: { "plaid" => { "pending" => true } })
+ assert Transaction.find(@entry.entryable_id).pending?, "fixture must read as pending"
+
+ assert_not stale.split_once!([ { name: "A", amount: 60 }, { name: "B", amount: 40 } ])
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "split_once! skips a transaction that became a transfer in the meantime" do
+ stale = Entry.find(@entry.id)
+ Transaction.where(id: @entry.entryable_id).update_all(kind: "funds_movement")
+ assert Transaction.find(@entry.entryable_id).transfer?, "fixture must read as a transfer"
+
+ assert_not stale.split_once!([ { name: "A", amount: 60 }, { name: "B", amount: 40 } ])
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "resplit! replaces the children of a split" do
+ @entry.split!([ { name: "A", amount: 60 }, { name: "B", amount: 40 } ])
+
+ assert @entry.resplit!([ { name: "C", amount: 30 }, { name: "D", amount: 70 } ])
+ assert_equal %w[C D], @entry.reload.child_entries.order(:name).pluck(:name)
+ assert @entry.excluded?
+ end
+
+ test "resplit! does not resurrect a split another caller removed" do
+ @entry.split!([ { name: "A", amount: 60 }, { name: "B", amount: 40 } ])
+ stale = Entry.find(@entry.id)
+ @entry.unsplit!
+
+ assert_not stale.resplit!([ { name: "C", amount: 30 }, { name: "D", amount: 70 } ])
+ assert_not @entry.reload.split_parent?
+ assert_not @entry.excluded?
+ end
+
+ test "unsplit_once! unsplits once and then reports nothing to do" do
+ @entry.split!([ { name: "A", amount: 60 }, { name: "B", amount: 40 } ])
+ stale = Entry.find(@entry.id)
+
+ assert @entry.unsplit_once!
+ assert_not stale.unsplit_once!
+ assert_not @entry.reload.split_parent?
+ end
end
diff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rb
index 3a300c5bba..8ed9ea489b 100644
--- a/test/models/family/data_exporter_test.rb
+++ b/test/models/family/data_exporter_test.rb
@@ -496,6 +496,77 @@ class Family::DataExporterTest < ActiveSupport::TestCase
end
end
+ test "split rule round-trips through NDJSON into another family" do
+ split_rule = create_split_rule!
+
+ Zip::File.open_buffer(@exporter.generate_export) do |zip|
+ rule_line = zip.read("all.ndjson").split("\n").find do |line|
+ parsed = JSON.parse(line)
+ parsed["type"] == "Rule" && parsed["data"]["name"] == split_rule.name
+ end
+
+ exported_value = JSON.parse(rule_line)["data"]["actions"].first["value"].to_json
+ refute_includes exported_value, @category.id
+ refute_includes exported_value, @tag.id
+
+ existing_category = @other_family.categories.create!(name: "Test Category", color: "#FF0000")
+
+ Family::DataImporter.new(@other_family, rule_line).import!
+
+ assert_imported_split_rule(split_rule.name, category: existing_category)
+ end
+ end
+
+ test "split rule round-trips through rules CSV into another family" do
+ split_rule = create_split_rule!
+
+ Zip::File.open_buffer(@exporter.generate_export) do |zip|
+ import = @other_family.imports.create!(type: "RuleImport", raw_file_str: zip.read("rules.csv"), col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+
+ assert_imported_split_rule(split_rule.name, category: @other_family.categories.find_by!(name: "Test Category"))
+ end
+ end
+
+ test "split rule with quotes in its names round-trips through rules CSV" do
+ @category.update!(name: 'Kids "Fun" \\ Stuff')
+ split_rule = create_split_rule!(row_name: 'My "half"')
+
+ Zip::File.open_buffer(@exporter.generate_export) do |zip|
+ import = @other_family.imports.create!(type: "RuleImport", raw_file_str: zip.read("rules.csv"), col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+
+ mine = imported_split_config(split_rule.name).first
+ assert_equal 'My "half"', mine["name"]
+ assert_equal @other_family.categories.find_by!(name: 'Kids "Fun" \\ Stuff').id, mine["category_id"]
+ end
+ end
+
+ test "exports a split rule whose category was deleted without the stale id" do
+ split_rule = create_split_rule!
+ @category.destroy!
+
+ Zip::File.open_buffer(@exporter.generate_export) do |zip|
+ rule_line = zip.read("all.ndjson").split("\n").find do |line|
+ parsed = JSON.parse(line)
+ parsed["type"] == "Rule" && parsed["data"]["name"] == split_rule.name
+ end
+
+ splits = JSON.parse(rule_line)["data"]["actions"].first["value"]["splits"]
+ assert_not splits.first.key?("category")
+ assert_not splits.first.key?("category_id")
+ assert_equal [ "Test Tag" ], splits.first["tags"]
+
+ Family::DataImporter.new(@other_family, rule_line).import!
+
+ split = imported_split_config(split_rule.name).first
+ assert_nil split["category_id"]
+ assert_equal [ @other_family.tags.find_by!(name: "Test Tag").id ], split["tag_ids"]
+ end
+ end
+
test "exports rule condition value refs for mapped operands" do
category_rule = @family.rules.build(
name: "Category Condition Rule",
@@ -1192,6 +1263,41 @@ class Family::DataExporterTest < ActiveSupport::TestCase
)
end
+ def create_split_rule!(row_name: "Mine")
+ merchant = @family.merchants.create!(name: "Split Merchant")
+ rule = @family.rules.build(name: "Split Rule", resource_type: "transaction", active: true)
+ rule.conditions.build(condition_type: "transaction_name", operator: "like", value: "shared")
+ rule.actions.build(
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "percentage", name: row_name, share: "60", category_id: @category.id, merchant_id: merchant.id, tag_ids: [ @tag.id ] },
+ { type: "percentage", name: "Theirs", share: "40", category_id: nil, merchant_id: nil, tag_ids: [] }
+ ]
+ }.to_json
+ )
+ rule.save!
+ rule
+ end
+
+ def imported_split_config(rule_name)
+ action = @other_family.rules.find_by!(name: rule_name).actions.sole
+ assert_equal "split_transaction", action.action_type
+ JSON.parse(action.value)["splits"]
+ end
+
+ def assert_imported_split_rule(rule_name, category:)
+ mine, theirs = imported_split_config(rule_name)
+
+ assert_equal [ "percentage", "Mine", "60" ], mine.values_at("type", "name", "share")
+ assert_equal category.id, mine["category_id"]
+ assert_equal @other_family.merchants.find_by!(name: "Split Merchant").id, mine["merchant_id"]
+ assert_equal [ @other_family.tags.find_by!(name: "Test Tag").id ], mine["tag_ids"]
+ assert_nil theirs["category_id"]
+ assert_nil theirs["merchant_id"]
+ assert_equal [], theirs["tag_ids"]
+ end
+
def create_csv_export_trade!
security = Security.create!(
ticker: "CSV#{SecureRandom.hex(3).upcase}",
diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rb
index 8fe9c2c7a9..57e06c6838 100644
--- a/test/models/family/data_importer_test.rb
+++ b/test/models/family/data_importer_test.rb
@@ -2435,6 +2435,124 @@ class Family::DataImporterTest < ActiveSupport::TestCase
assert_equal weekly_tag.id, rule.actions.first.value
end
+ test "rejects a split rule action with invalid text before creating related records" do
+ counts = [ @family.rules.count, @family.categories.count, @family.merchants.count, @family.tags.count ]
+
+ [ { name: "Bad\0Name" }, { category: "Bad\0Category" }, { merchant: "Bad\0Merchant" }, { tags: [ "Safe", "Bad\0Tag" ] } ].each do |bad|
+ ndjson = build_ndjson([ {
+ type: "Rule", version: 1,
+ data: {
+ name: "Invalid split", resource_type: "transaction",
+ conditions: [ { condition_type: "transaction_name", operator: "like", value: "rent" } ],
+ actions: [ {
+ action_type: "split_transaction",
+ value: { splits: [
+ { type: "percentage", name: "A", share: "50" }.merge(bad),
+ { type: "percentage", name: "B", share: "50" }
+ ] }.to_json
+ } ]
+ }
+ } ])
+
+ error = assert_raises(Family::DataImporter::InvalidRecordError, bad.inspect) do
+ Family::DataImporter.new(@family, ndjson).import!
+ end
+
+ assert_equal "value", error.details[:field]
+ assert_equal counts, [ @family.rules.count, @family.categories.count, @family.merchants.count, @family.tags.count ]
+ end
+ end
+
+ test "imports a split rule action whose rows carry foreign ids by dropping them" do
+ foreign_category = categories(:food_and_drink)
+ own_tag = @family.tags.create!(name: "Shared")
+
+ ndjson = build_ndjson([
+ {
+ type: "Rule",
+ version: 1,
+ data: {
+ name: "Split With Foreign Ids",
+ resource_type: "transaction",
+ active: true,
+ conditions: [ { condition_type: "transaction_name", operator: "like", value: "rent" } ],
+ actions: [
+ {
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "percentage", name: "A", share: "50", category_id: foreign_category.id, tag_ids: [ own_tag.id, SecureRandom.uuid ] },
+ { type: "percentage", name: "B", share: "50", category: "Housing" }
+ ]
+ }.to_json
+ }
+ ]
+ }
+ }
+ ])
+
+ Family::DataImporter.new(@family, ndjson).import!
+
+ first, second = JSON.parse(@family.rules.find_by!(name: "Split With Foreign Ids").actions.sole.value)["splits"]
+ assert_nil first["category_id"]
+ assert_equal [ own_tag.id ], first["tag_ids"]
+ assert_equal @family.categories.find_by!(name: "Housing").id, second["category_id"]
+ end
+
+ test "remaps raw split ids from an older export through the imported records" do
+ ndjson = build_ndjson([
+ { type: "Category", data: { id: "source-category", name: "Groceries", color: "#407706" } },
+ { type: "Tag", data: { id: "source-tag", name: "Shared", color: "#00FF00" } },
+ {
+ type: "Rule",
+ version: 1,
+ data: {
+ name: "Raw Id Split",
+ resource_type: "transaction",
+ active: true,
+ conditions: [ { condition_type: "transaction_name", operator: "like", value: "market" } ],
+ actions: [
+ {
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "percentage", name: "A", share: "50", category_id: "source-category", tag_ids: [ "source-tag" ] },
+ { type: "percentage", name: "B", share: "50" }
+ ]
+ }.to_json
+ }
+ ]
+ }
+ }
+ ])
+
+ Family::DataImporter.new(@family, ndjson).import!
+
+ first = JSON.parse(@family.rules.find_by!(name: "Raw Id Split").actions.sole.value)["splits"].first
+ assert_equal @family.categories.find_by!(name: "Groceries").id, first["category_id"]
+ assert_equal [ @family.tags.find_by!(name: "Shared").id ], first["tag_ids"]
+ end
+
+ test "rejects a non-string split value with a validation error" do
+ ndjson = build_ndjson([
+ {
+ type: "Rule",
+ version: 1,
+ data: {
+ name: "Scalar Split",
+ resource_type: "transaction",
+ active: true,
+ conditions: [ { condition_type: "transaction_name", operator: "like", value: "x" } ],
+ actions: [ { action_type: "split_transaction", value: 5 } ]
+ }
+ }
+ ])
+
+ assert_raises(ActiveRecord::RecordInvalid) do
+ Family::DataImporter.new(@family, ndjson).import!
+ end
+ end
+
test "preserves explicit false rule operand values" do
importer = Family::DataImporter.new(@family, "")
diff --git a/test/models/rule/action_executor/split_transaction_concurrency_test.rb b/test/models/rule/action_executor/split_transaction_concurrency_test.rb
new file mode 100644
index 0000000000..98537f2176
--- /dev/null
+++ b/test/models/rule/action_executor/split_transaction_concurrency_test.rb
@@ -0,0 +1,54 @@
+require "test_helper"
+require "concurrent"
+
+# Two split rules running against the same transaction at the same time must
+# split it once, not twice. Real threads on real connections, so this needs
+# real commits.
+class Rule::ActionExecutor::SplitTransactionConcurrencyTest < ActiveSupport::TestCase
+ self.use_transactional_tests = false
+
+ setup do
+ @family = Family.create!(name: "Split Race", currency: "USD")
+ @account = Account.create!(
+ family: @family, name: "Checking", currency: "USD",
+ balance: 0, accountable: Depository.new)
+ @entry = Entry.create!(
+ account: @account, name: "Bundle", date: Date.current,
+ amount: 100, currency: "USD", entryable: Transaction.new)
+ @rule = @family.rules.create!(
+ resource_type: "transaction",
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+ end
+
+ teardown do
+ Entry.where(account_id: @account.id).where.not(parent_entry_id: nil).delete_all
+ Entry.where(account_id: @account.id).delete_all
+ Rule.where(family_id: @family.id).destroy_all
+ @account.destroy
+ @family.destroy
+ end
+
+ test "concurrent split rules split a transaction only once" do
+ value = { splits: [
+ { name: "Half A", share: "50", type: "fixed" },
+ { name: "Half B", share: "50", type: "fixed" }
+ ] }.to_json
+ latch = Concurrent::CountDownLatch.new(2)
+
+ 2.times.map do
+ Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ action = Rule::Action.new(rule: @rule, action_type: "split_transaction", value: value)
+ scope = @account.transactions
+ latch.count_down
+ latch.wait(5)
+ action.apply(scope)
+ end
+ end
+ end.each(&:join)
+
+ children = Entry.where(parent_entry_id: @entry.id)
+ assert_equal 2, children.count, "the parent must be split exactly once"
+ assert_equal 100, children.sum(:amount)
+ end
+end
diff --git a/test/models/rule/action_executor/split_transaction_test.rb b/test/models/rule/action_executor/split_transaction_test.rb
new file mode 100644
index 0000000000..d255a80c78
--- /dev/null
+++ b/test/models/rule/action_executor/split_transaction_test.rb
@@ -0,0 +1,342 @@
+require "test_helper"
+
+class Rule::ActionExecutor::SplitTransactionTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = families(:dylan_family)
+ @rule = rules(:one)
+ @account = @family.accounts.create!(name: "Split rule test", balance: 1000, currency: "USD", accountable: Depository.new)
+
+ @groceries = @family.categories.create!(name: "Split Groceries")
+ @household = @family.categories.create!(name: "Split Household")
+
+ @rule_scope = @account.transactions
+ end
+
+ # `type:` sets a shared split type on every row that doesn't declare its own (most tests use
+ # one type throughout); pass per-row `type:` in `splits` directly to test a mixed config.
+ def build_action(splits:, type: nil)
+ splits = splits.map { |split| split[:type] ? split : split.merge(type: type) } if type
+ Rule::Action.new(rule: @rule, action_type: "split_transaction", value: { splits: splits }.to_json)
+ end
+
+ test "fixed split applies per-split merchant and tags" do
+ merchant = @family.merchants.create!(name: "Split merchant", type: "FamilyMerchant")
+ tag = @family.tags.create!(name: "Split tag")
+ entry = create_transaction(amount: 100, name: "Bundle", account: @account)
+
+ action = build_action(
+ type: "fixed",
+ splits: [
+ { name: "Groceries", share: "70", merchant_id: merchant.id, tag_ids: [ tag.id ] },
+ { name: "Household", share: "30" }
+ ]
+ )
+
+ action.apply(@rule_scope)
+
+ entry.reload
+ with_merchant = entry.child_entries.find_by(amount: 70)
+ without_merchant = entry.child_entries.find_by(amount: 30)
+
+ assert_equal merchant.id, with_merchant.transaction.merchant_id
+ assert_equal [ tag ], with_merchant.transaction.tags
+ assert_equal [], without_merchant.transaction.tags
+ end
+
+ test "percentage split rounds to the currency's minor unit" do
+ yen_account = @family.accounts.create!(name: "Yen split test", balance: 0, currency: "JPY", accountable: Depository.new)
+ entry = create_transaction(amount: 100, currency: "JPY", name: "Bundle", account: yen_account)
+
+ build_action(type: "percentage", splits: [
+ { name: "A", share: "33.33" }, { name: "B", share: "33.33" }, { name: "C", share: "33.34" }
+ ]).apply(yen_account.transactions)
+
+ amounts = entry.reload.child_entries.order(:name).pluck(:amount)
+ assert_equal [ 33, 33, 34 ], amounts
+ assert amounts.all? { |amount| amount == amount.round }, "no fractional yen: #{amounts.inspect}"
+ end
+
+ test "amount precision follows the currency, capped at the stored scale" do
+ klass = Rule::ActionExecutor::SplitTransaction
+ assert_equal 0, klass.amount_precision("JPY")
+ assert_equal 2, klass.amount_precision("EUR")
+ assert_equal 3, klass.amount_precision("KWD")
+ assert_equal 4, klass.amount_precision("BTC"), "entries.amount stores 4 decimals"
+ assert_equal 2, klass.amount_precision("XXQ"), "unknown codes fall back to cents"
+ end
+
+ test "ignores a merchant and tags that don't belong to the family" do
+ other_family_merchant = families(:empty).merchants.create!(name: "Foreign merchant", type: "FamilyMerchant")
+ other_family_tag = families(:empty).tags.create!(name: "Foreign tag")
+ entry = create_transaction(amount: 100, name: "Bundle", account: @account)
+
+ action = build_action(
+ type: "fixed",
+ splits: [
+ { name: "Part 1", share: "70", merchant_id: other_family_merchant.id, tag_ids: [ other_family_tag.id ] },
+ { name: "Part 2", share: "30" }
+ ]
+ )
+
+ action.apply(@rule_scope)
+
+ entry.reload
+ child = entry.child_entries.find_by(amount: 70)
+ assert_nil child.transaction.merchant_id
+ assert_equal [], child.transaction.tags
+ end
+
+ test "value_display summarizes the split configuration" do
+ action = build_action(
+ type: "percentage",
+ splits: [ { name: "A", share: "60" }, { name: "B", share: "40" } ]
+ )
+
+ assert_equal "2 splits", action.value_display
+ end
+
+ test "fixed split creates children with correct amounts and categories" do
+ entry = create_transaction(amount: 100, name: "Bundle", account: @account)
+
+ action = build_action(
+ type: "fixed",
+ splits: [
+ { name: "Groceries", share: "70", category_id: @groceries.id },
+ { name: "Household", share: "30", category_id: @household.id }
+ ]
+ )
+
+ modified = action.apply(@rule_scope)
+
+ assert_equal 1, modified
+ entry.reload
+ assert entry.split_parent?
+ assert entry.excluded?
+
+ children = entry.child_entries.order(:amount)
+ assert_equal [ 30, 70 ], children.map(&:amount)
+ assert_equal [ @household.id, @groceries.id ], children.map { |c| c.transaction.category_id }
+ end
+
+ test "percentage split rounds correctly and sums to the exact original amount" do
+ entry = create_transaction(amount: 100.01, name: "Bundle", account: @account)
+
+ action = build_action(
+ type: "percentage",
+ splits: [
+ { name: "Part 1", share: "33.33" },
+ { name: "Part 2", share: "33.33" },
+ { name: "Part 3", share: "33.34" }
+ ]
+ )
+
+ action.apply(@rule_scope)
+
+ entry.reload
+ children = entry.child_entries
+ assert_equal 3, children.size
+ assert_equal entry.amount, children.sum(&:amount)
+ end
+
+ test "fixed split skips a transaction whose amount doesn't match the configured shares" do
+ matching = create_transaction(amount: 100, name: "Bundle A", account: @account)
+ mismatched = create_transaction(amount: 55, name: "Bundle B", account: @account)
+
+ action = build_action(
+ type: "fixed",
+ splits: [
+ { name: "Part 1", share: "70" },
+ { name: "Part 2", share: "30" }
+ ]
+ )
+
+ modified = nil
+ assert_difference "DebugLogEntry.count", 1 do
+ modified = action.apply(@rule_scope)
+ end
+
+ assert_equal 1, modified
+ assert matching.reload.split_parent?
+ refute mismatched.reload.split_parent?
+
+ entry = DebugLogEntry.order(:created_at).last
+ assert_equal "rule_run", entry.category
+ assert_equal "warn", entry.level
+ assert_equal "Rule::ActionExecutor::SplitTransaction", entry.source
+ assert_equal @family, entry.family
+ assert_equal 1, entry.metadata["skipped_count"]
+ assert_equal "unresolvable_split_amounts", entry.metadata["skipped"].first["reason"]
+ end
+
+ test "percentage split skips a transaction when rounding drift would create a non-positive amount" do
+ entry = create_transaction(amount: 0.02, name: "Tiny bundle", account: @account)
+
+ # A valid 100% split (unlike a mismatched total, this could actually pass save-time
+ # validation): the first two shares round up to $0.01 each against a $0.02 total, leaving
+ # $0.00 for the third split, which absorbs whatever's left.
+ action = build_action(
+ type: "percentage",
+ splits: [
+ { name: "Part 1", share: "33.33" },
+ { name: "Part 2", share: "33.33" },
+ { name: "Part 3", share: "33.34" }
+ ]
+ )
+
+ modified = nil
+ assert_difference "DebugLogEntry.count", 1 do
+ modified = action.apply(@rule_scope)
+ end
+
+ assert_equal 0, modified
+ refute entry.reload.split_parent?
+ end
+
+ test "skips transactions that are not splittable" do
+ transfer = create_transfer(from_account: @account, to_account: accounts(:credit_card), amount: 40)
+ pending = create_transaction(amount: 40, name: "Pending", account: @account)
+ pending.transaction.update!(extra: { "simplefin" => { "pending" => true } })
+ excluded = create_transaction(amount: 40, name: "Excluded", account: @account, excluded: true)
+ already_split = create_transaction(amount: 40, name: "Already split", account: @account)
+ already_split.split!([ { name: "A", amount: 20 }, { name: "B", amount: 20 } ])
+
+ action = build_action(
+ type: "fixed",
+ splits: [
+ { name: "Part 1", share: "20" },
+ { name: "Part 2", share: "20" }
+ ]
+ )
+
+ modified = action.apply(@rule_scope)
+
+ assert_equal 0, modified
+ refute transfer.outflow_transaction.entry.reload.split_parent?
+ refute pending.reload.split_parent?
+ refute excluded.reload.split_parent?
+ assert_equal 2, already_split.reload.child_entries.count
+ end
+
+ test "does nothing for a stored config whose rows are not objects" do
+ entry = create_transaction(amount: 100, name: "Malformed rows", account: @account)
+ action = Rule::Action.new(rule: @rule, action_type: "split_transaction", value: { splits: [ nil, nil ] }.to_json)
+
+ assert_equal 0, action.apply(@rule_scope)
+ assert_equal "", action.value_display
+ refute entry.reload.split_parent?
+ end
+
+ test "ignores a category id that doesn't belong to the family" do
+ other_family_category = families(:empty).categories.create!(name: "Other family category")
+ entry = create_transaction(amount: 100, name: "Bundle", account: @account)
+
+ action = build_action(
+ type: "fixed",
+ splits: [
+ { name: "Part 1", share: "70", category_id: other_family_category.id },
+ { name: "Part 2", share: "30" }
+ ]
+ )
+
+ action.apply(@rule_scope)
+
+ entry.reload
+ child = entry.child_entries.find_by(amount: 70)
+ assert_nil child.transaction.category_id
+ end
+
+ test "income transactions produce negative child amounts" do
+ entry = create_transaction(amount: -100, name: "Refund bundle", account: @account)
+
+ action = build_action(
+ type: "percentage",
+ splits: [
+ { name: "Part 1", share: "60" },
+ { name: "Part 2", share: "40" }
+ ]
+ )
+
+ action.apply(@rule_scope)
+
+ entry.reload
+ assert_equal [ -60, -40 ], entry.child_entries.order(amount: :asc).pluck(:amount).map(&:to_i)
+ assert_equal(-100, entry.child_entries.sum(&:amount))
+ end
+
+ test "does not re-split an already-split transaction on re-apply" do
+ entry = create_transaction(amount: 100, name: "Bundle", account: @account)
+
+ action = build_action(
+ type: "fixed",
+ splits: [
+ { name: "Part 1", share: "70" },
+ { name: "Part 2", share: "30" }
+ ]
+ )
+
+ action.apply(@rule_scope)
+ assert_equal 2, entry.reload.child_entries.count
+
+ second_pass = action.apply(@rule_scope)
+
+ assert_equal 0, second_pass
+ assert_equal 2, entry.reload.child_entries.count
+ end
+
+ test "mixed split takes fixed amounts off the top, then divides the remainder by percentage" do
+ entry = create_transaction(amount: 100, name: "Bundle", account: @account)
+
+ action = build_action(
+ splits: [
+ { type: "fixed", name: "Processing fee", share: "5", category_id: @household.id },
+ { type: "percentage", name: "Groceries", share: "100", category_id: @groceries.id }
+ ]
+ )
+
+ action.apply(@rule_scope)
+
+ entry.reload
+ fee = entry.child_entries.find_by(amount: 5)
+ rest = entry.child_entries.find_by(amount: 95)
+
+ assert_equal @household.id, fee.transaction.category_id
+ assert_equal @groceries.id, rest.transaction.category_id
+ end
+
+ test "mixed split divides the post-fixed remainder proportionally across multiple percentage rows" do
+ entry = create_transaction(amount: 110, name: "Bundle", account: @account)
+
+ action = build_action(
+ splits: [
+ { type: "fixed", name: "Fee", share: "10" },
+ { type: "percentage", name: "Part A", share: "60" },
+ { type: "percentage", name: "Part B", share: "40" }
+ ]
+ )
+
+ action.apply(@rule_scope)
+
+ entry.reload
+ children = entry.child_entries.order(:amount)
+ # $100 remains after the $10 fee; 60/40 of that is $60/$40.
+ assert_equal [ 10, 40, 60 ], children.map(&:amount)
+ end
+
+ test "mixed split skips a transaction where fixed amounts exceed the total, leaving nothing for percentages" do
+ entry = create_transaction(amount: 10, name: "Small bundle", account: @account)
+
+ action = build_action(
+ splits: [
+ { type: "fixed", name: "Fee", share: "20" },
+ { type: "percentage", name: "Rest", share: "100" }
+ ]
+ )
+
+ modified = action.apply(@rule_scope)
+
+ assert_equal 0, modified
+ refute entry.reload.split_parent?
+ end
+end
diff --git a/test/models/rule/action_test.rb b/test/models/rule/action_test.rb
index e2a5efa2bb..b47cbb1fc5 100644
--- a/test/models/rule/action_test.rb
+++ b/test/models/rule/action_test.rb
@@ -292,4 +292,316 @@ class Rule::ActionTest < ActiveSupport::TestCase
assert_equal 0, result
assert_nil @txn1.reload.investment_activity_label
end
+
+ test "split_transaction builds value from split_rows form fields" do
+ tag = @family.tags.create!(name: "Split test tag")
+
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ split_rows: {
+ "0" => { type: "percentage", name: "Groceries", share: "70", category_id: @grocery_category.id, merchant_id: @whole_foods_merchant.id, tag_ids: [ tag.id, "" ] },
+ "1" => { type: "percentage", name: "Household", share: "30", category_id: "", merchant_id: "", tag_ids: [ "" ] }
+ }
+ )
+
+ assert action.valid?, action.errors.full_messages.to_sentence
+
+ parsed = JSON.parse(action.value)
+ assert_equal [ "Groceries", "Household" ], parsed["splits"].map { |s| s["name"] }
+ assert_equal [ "percentage", "percentage" ], parsed["splits"].map { |s| s["type"] }
+ assert_equal @grocery_category.id, parsed["splits"].first["category_id"]
+ assert_nil parsed["splits"].last["category_id"]
+ assert_equal @whole_foods_merchant.id, parsed["splits"].first["merchant_id"]
+ assert_nil parsed["splits"].last["merchant_id"]
+ assert_equal [ tag.id ], parsed["splits"].first["tag_ids"]
+ assert_equal [], parsed["splits"].last["tag_ids"]
+ end
+
+ test "split_transaction rejects malformed JSON" do
+ action = Rule::Action.new(rule: @transaction_rule, action_type: "split_transaction", value: "not json")
+
+ assert_not action.valid?
+ assert_includes action.errors[:value], "must be a valid split configuration"
+ end
+
+ test "split_transaction rejects fewer than two splits" do
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: { splits: [ { type: "fixed", name: "Only one", share: "10" } ] }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value], "must have between 2 and 20 splits"
+ end
+
+ test "split_transaction rejects an invalid split type" do
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: {
+ splits: [ { type: "bogus", name: "A", share: "50" }, { type: "percentage", name: "B", share: "50" } ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value], "split #1 type must be fixed or percentage"
+ end
+
+ test "split_transaction rejects percentages that don't add up to 100" do
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: {
+ splits: [ { type: "percentage", name: "A", share: "50" }, { type: "percentage", name: "B", share: "40" } ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value], "percentages must add up to 100 (got 90)"
+ end
+
+ test "split_transaction rejects a non-positive share" do
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: {
+ splits: [ { type: "fixed", name: "A", share: "0" }, { type: "fixed", name: "B", share: "10" } ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value], "split #1 share must be a positive number"
+ end
+
+ test "split_transaction rejects a fixed share with more decimals than amounts store" do
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: {
+ splits: [ { type: "fixed", name: "A", share: "10.12345" }, { type: "percentage", name: "B", share: "100" } ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value], "split #1 share must be a positive number"
+ end
+
+ test "split_transaction rejects a split name that the database cannot store" do
+ # A NUL byte, and a lone surrogate escape that JSON.parse turns into broken UTF-8.
+ [ "Bad\\u0000Name", "Bad\\udc00Name" ].each do |name|
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: %({"splits":[{"type":"percentage","name":"#{name}","share":"50"},{"type":"percentage","name":"B","share":"50"}]})
+ )
+
+ assert_not action.valid?, name.inspect
+ assert_includes action.errors[:value], "split #1 name contains invalid characters"
+ end
+ end
+
+ test "split_transaction rejects rows that are not objects without raising" do
+ [ [ nil, nil ], [ "A", "B" ], [ { type: "percentage", name: "A", share: "100" }, 42 ] ].each do |rows|
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: { splits: rows }.to_json
+ )
+
+ assert_not action.valid?, "expected #{rows.inspect} to be invalid"
+ assert_includes action.errors[:value], "must be a valid split configuration"
+ end
+ end
+
+ test "split_transaction rejects non-finite shares" do
+ [ "NaN", "Infinity", "-Infinity" ].each do |share|
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: {
+ splits: [ { type: "fixed", name: "A", share: share }, { type: "percentage", name: "B", share: "100" } ]
+ }.to_json
+ )
+
+ assert_not action.valid?, "expected share #{share} to be invalid"
+ assert_includes action.errors[:value], "split #1 share must be a positive number"
+ end
+ end
+
+ test "split_transaction rejects a category from another family" do
+ other_category = families(:empty).categories.create!(name: "Foreign category")
+
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "A", share: "10", category_id: other_category.id },
+ { type: "fixed", name: "B", share: "10" }
+ ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value], "split #1 category does not belong to this family"
+ end
+
+ test "split_transaction rejects a merchant from another family" do
+ other_merchant = families(:empty).merchants.create!(name: "Foreign merchant", type: "FamilyMerchant")
+
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "A", share: "10", merchant_id: other_merchant.id },
+ { type: "fixed", name: "B", share: "10" }
+ ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value], "split #1 merchant does not belong to this family"
+ end
+
+ test "split_transaction rejects a tag from another family" do
+ other_tag = families(:empty).tags.create!(name: "Foreign tag")
+
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "A", share: "10", tag_ids: [ other_tag.id ] },
+ { type: "fixed", name: "B", share: "10" }
+ ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value], "split #1 has a tag that does not belong to this family"
+ end
+
+ test "split_transaction accepts a valid percentage config" do
+ action = Rule::Action.new(
+ rule: @transaction_rule,
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "percentage", name: "Groceries", share: "70", category_id: @grocery_category.id },
+ { type: "percentage", name: "Household", share: "30" }
+ ]
+ }.to_json
+ )
+
+ assert action.valid?
+ end
+
+ test "split_transaction with only fixed splits requires an exact amount condition on the rule" do
+ rule_without_amount_condition = Rule.new(family: @family, resource_type: "transaction")
+
+ action = Rule::Action.new(
+ rule: rule_without_amount_condition,
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "Groceries", share: "70", category_id: @grocery_category.id },
+ { type: "fixed", name: "Household", share: "30" }
+ ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value],
+ "fixed-amount splits require a rule condition that matches an exact transaction amount (e.g. Amount = 42.00), otherwise the shares can't reliably sum to every matching transaction's total"
+ end
+
+ test "split_transaction with only fixed splits is valid with an exact amount condition on the rule" do
+ rule_with_amount_condition = Rule.new(
+ family: @family,
+ resource_type: "transaction",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_amount", operator: "=", value: 100) ]
+ )
+
+ action = Rule::Action.new(
+ rule: rule_with_amount_condition,
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "Groceries", share: "70", category_id: @grocery_category.id },
+ { type: "fixed", name: "Household", share: "30" }
+ ]
+ }.to_json
+ )
+
+ assert action.valid?
+ end
+
+ test "split_transaction with only fixed splits requires shares to sum to the exact amount condition's value" do
+ rule_with_amount_condition = Rule.new(
+ family: @family,
+ resource_type: "transaction",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_amount", operator: "=", value: 100) ]
+ )
+
+ action = Rule::Action.new(
+ rule: rule_with_amount_condition,
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "Groceries", share: "70", category_id: @grocery_category.id },
+ { type: "fixed", name: "Household", share: "20" }
+ ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ assert_includes action.errors[:value],
+ "split shares must add up to 100.0, the exact amount required by this rule's condition"
+ end
+
+ test "split_transaction with only fixed splits is not satisfied by an exact amount condition inside an OR group" do
+ rule_with_or_amount_condition = Rule.new(
+ family: @family,
+ resource_type: "transaction",
+ conditions: [
+ Rule::Condition.new(condition_type: "compound", operator: "any", sub_conditions: [
+ Rule::Condition.new(condition_type: "transaction_amount", operator: "=", value: 100),
+ Rule::Condition.new(condition_type: "transaction_name", operator: "=", value: "Foo")
+ ])
+ ]
+ )
+
+ action = Rule::Action.new(
+ rule: rule_with_or_amount_condition,
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "Groceries", share: "70", category_id: @grocery_category.id },
+ { type: "fixed", name: "Household", share: "30" }
+ ]
+ }.to_json
+ )
+
+ assert_not action.valid?
+ end
+
+ test "split_transaction with a percentage split does not require an exact amount condition" do
+ rule_without_amount_condition = Rule.new(family: @family, resource_type: "transaction")
+
+ action = Rule::Action.new(
+ rule: rule_without_amount_condition,
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "Fee", share: "5" },
+ { type: "percentage", name: "Rest", share: "100" }
+ ]
+ }.to_json
+ )
+
+ assert action.valid?, action.errors.full_messages.to_sentence
+ end
end
diff --git a/test/models/rule/runner_test.rb b/test/models/rule/runner_test.rb
index 1ae1571968..b80047bb0e 100644
--- a/test/models/rule/runner_test.rb
+++ b/test/models/rule/runner_test.rb
@@ -282,6 +282,26 @@ class Rule::RunnerTest < ActiveSupport::TestCase
assert_equal @dining, @whole_foods.reload.category
end
+ test "a split rule higher up keeps the categories it gives the children" do
+ split = { splits: [
+ { type: "percentage", name: "Whole Foods groceries", share: "50", category_id: @groceries.id },
+ { type: "percentage", name: "Whole Foods other", share: "50" }
+ ] }
+ @family.rules.create!(
+ name: "Split", resource_type: "transaction", active: true,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
+ actions: [ Rule::Action.new(action_type: "split_transaction", value: split.to_json) ]
+ )
+ create_rule("Bottom", "Whole Foods", category: @dining)
+
+ run_active_rules
+
+ children = @whole_foods.entry.reload.child_entries.index_by(&:name)
+ assert_equal @groceries, children["Whole Foods groceries"].transaction.category
+ # The split set no category here, so the rule below still may.
+ assert_equal @dining, children["Whole Foods other"].transaction.category
+ end
+
test "raises LockBusy while another run holds the family lock" do
create_rule("Top", "Whole Foods", category: @groceries)
diff --git a/test/models/rule_import_test.rb b/test/models/rule_import_test.rb
index 4cc3099913..e785354c36 100644
--- a/test/models/rule_import_test.rb
+++ b/test/models/rule_import_test.rb
@@ -215,6 +215,46 @@ class RuleImportTest < ActiveSupport::TestCase
assert_equal [ existing_tag.id, comma_tag.id ], action.value.split(",")
end
+ test "imports a split action by mapping row category, merchant and tag names to ids" do
+ actions = [
+ {
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "percentage", name: "Food", share: "70", category: "Groceries", merchant: "Corner Shop", tags: [ "Shared" ] },
+ { type: "percentage", name: "Other", share: "30", category_id: categories(:food_and_drink).id }
+ ]
+ }
+ }
+ ].to_json
+ csv = CSV.generate do |rows|
+ rows << %w[name resource_type active effective_date conditions actions]
+ rows << [ "Split groceries", "transaction", "true", "", '[{"condition_type":"transaction_name","operator":"like","value":"market"}]', actions ]
+ end
+
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+
+ food, other = JSON.parse(Rule.find_by!(family: @family, name: "Split groceries").actions.sole.value)["splits"]
+ assert_equal @category.id, food["category_id"]
+ assert_equal @family.merchants.find_by!(name: "Corner Shop").id, food["merchant_id"]
+ assert_equal [ Tag.find_by!(family: @family, name: "Shared").id ], food["tag_ids"]
+ # A raw id that belongs to the importing family is kept as is
+ assert_equal categories(:food_and_drink).id, other["category_id"]
+ end
+
+ test "csv template rows import, including the split example" do
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: RuleImport.new.csv_template.to_csv, col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+
+ splits = JSON.parse(Rule.find_by!(family: @family, name: "Split shared rent").actions.sole.value)["splits"]
+ rent = @family.categories.find_by!(name: "Rent")
+ assert_equal [ rent.id, rent.id ], splits.map { |split| split["category_id"] }
+ assert_equal [ @family.tags.find_by!(name: "Shared").id ], splits.last["tag_ids"]
+ end
+
test "imports transaction_tag condition and maps tag name to id" do
existing_tag = @family.tags.create!(name: "Existing Tag")
@@ -485,6 +525,34 @@ class RuleImportTest < ActiveSupport::TestCase
assert_nil @family.rules.find_by(name: "Invalid condition rule")
end
+ test "reports a validation error for a null byte inside a split action" do
+ split = { splits: [
+ { type: "percentage", name: "A", share: "50", category: "Bad\0Category" },
+ { type: "percentage", name: "B", share: "50" }
+ ] }
+ category_count = @family.categories.count
+
+ # As an object and as a JSON string (where the NUL byte is escaped in the raw text).
+ [ split, split.to_json ].each do |value|
+ csv = CSV.generate do |rows|
+ rows << %w[name resource_type active effective_date conditions actions]
+ rows << [
+ "Invalid split rule", "transaction", true, nil,
+ [ { condition_type: "transaction_name", operator: "like", value: "rent" } ].to_json,
+ [ { action_type: "split_transaction", value: value } ].to_json
+ ]
+ end
+
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
+ import.generate_rows_from_csv
+
+ error = assert_raises(ActiveRecord::RecordInvalid, value.class.name) { import.send(:import!) }
+ assert_match(/value is invalid/i, error.message)
+ assert_nil @family.rules.find_by(name: "Invalid split rule")
+ assert_equal category_count, @family.categories.count
+ end
+ end
+
test "rejects an imported name with a trailing null byte" do
import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
import.generate_rows_from_csv
diff --git a/test/models/rule_test.rb b/test/models/rule_test.rb
index 11a3c34aea..5d1780588e 100644
--- a/test/models/rule_test.rb
+++ b/test/models/rule_test.rb
@@ -121,7 +121,13 @@ class RuleTest < ActiveSupport::TestCase
rule = @family.rules.build(resource_type: "transaction")
action = rule.actions.build(action_type: key)
- assert rule.valid?, "#{key}: #{rule.errors.full_messages.to_sentence}"
+ # A split action is only valid with a split configuration in `value`;
+ # its action_type is still accepted.
+ if key == "split_transaction"
+ rule.valid?
+ else
+ assert rule.valid?, "#{key}: #{rule.errors.full_messages.to_sentence}"
+ end
assert_empty action.errors[:action_type], key
end
end
@@ -176,6 +182,60 @@ class RuleTest < ActiveSupport::TestCase
assert_equal @groceries_category, transaction_entry.transaction.category
end
+ test "split_transaction rule end to end" do
+ transaction_entry = create_transaction(
+ date: Date.current,
+ amount: 100,
+ account: @account,
+ name: "Netflix+Hulu Bundle"
+ )
+
+ hulu_category = @family.categories.create!(name: "Streaming")
+
+ rule = Rule.create!(
+ family: @family,
+ resource_type: "transaction",
+ effective_date: 1.day.ago.to_date,
+ conditions: [
+ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Netflix+Hulu Bundle"),
+ Rule::Condition.new(condition_type: "transaction_amount", operator: "=", value: 100)
+ ],
+ actions: [
+ Rule::Action.new(
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "Netflix", share: "70", category_id: @groceries_category.id },
+ { type: "fixed", name: "Hulu", share: "30", category_id: hulu_category.id }
+ ]
+ }.to_json
+ )
+ ]
+ )
+
+ rule.apply
+
+ transaction_entry.reload
+ assert transaction_entry.split_parent?
+ assert_equal [ 30, 70 ], transaction_entry.child_entries.order(:amount).pluck(:amount).map(&:to_i)
+ end
+
+ test "a split rule cannot have other actions" do
+ split = { splits: [ { type: "percentage", name: "A", share: "50" }, { type: "percentage", name: "B", share: "50" } ] }
+
+ rule = @family.rules.build(
+ resource_type: "transaction",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Bundle") ],
+ actions: [
+ Rule::Action.new(action_type: "split_transaction", value: split.to_json),
+ Rule::Action.new(action_type: "set_transaction_category", value: @groceries_category.id)
+ ]
+ )
+
+ assert_not rule.valid?
+ assert_includes rule.errors[:base], I18n.t("activerecord.errors.models.rule.split_not_alone")
+ end
+
test "compound rule" do
transaction_entry1 = create_transaction(date: Date.current, amount: 50, account: @account, merchant: @whole_foods_merchant)
transaction_entry2 = create_transaction(date: Date.current, amount: 100, account: @account, merchant: @whole_foods_merchant)
diff --git a/test/system/rules_test.rb b/test/system/rules_test.rb
index 08d6d8d5a2..73f7f5114e 100644
--- a/test/system/rules_test.rb
+++ b/test/system/rules_test.rb
@@ -80,6 +80,89 @@ class RulesTest < ApplicationSystemTestCase
assert_text "Nicht unterstützt (name)"
end
+ test "fixed split summary follows edits to the exact amount condition" do
+ rule = @user.family.rules.create!(
+ name: "Fixed split",
+ resource_type: "transaction",
+ conditions: [
+ Rule::Condition.new(condition_type: "transaction_amount", operator: "=", value: "100")
+ ],
+ actions: [
+ Rule::Action.new(
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "fixed", name: "A", share: "70" },
+ { type: "fixed", name: "B", share: "30" }
+ ]
+ }.to_json
+ )
+ ]
+ )
+
+ visit edit_rule_path(rule)
+
+ within "dialog" do
+ summary = find("[data-rule--split-action-target='summary']")
+ assert_selector "[data-rule--split-action-target='summary'].text-success", text: "100.00 / 100.00"
+
+ find("[data-rules-target='conditionsList'] input[name$='[value]']").fill_in(with: "120")
+
+ assert_selector "[data-rule--split-action-target='summary'].text-destructive", text: "100.00 / 120.00"
+ assert_no_selector "[data-rule--split-action-target='summary'].text-success"
+ assert_equal "100.00 / 120.00", summary.text
+ end
+ end
+
+ test "split rows save category, merchant and tags picked in the rule form" do
+ merchant = @user.family.merchants.create!(name: "Split Landlord")
+ rule = @user.family.rules.create!(
+ name: "Percentage split",
+ resource_type: "transaction",
+ conditions: [
+ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "rent")
+ ],
+ actions: [
+ Rule::Action.new(
+ action_type: "split_transaction",
+ value: {
+ splits: [
+ { type: "percentage", name: "Mine", share: "50" },
+ { type: "percentage", name: "Theirs", share: "50" }
+ ]
+ }.to_json
+ )
+ ]
+ )
+
+ visit edit_rule_path(rule)
+
+ within "dialog" do
+ first_row = all("[data-rule--split-action-target='row']", minimum: 2).first
+
+ within first_row do
+ find("select[aria-label='Split category']").select(categories(:food_and_drink).name)
+ find("select[aria-label='Split merchant']").select(merchant.name)
+ find("button[aria-label='Split tags']").click
+ find("[role='option'][data-tag-name='#{tags(:one).name}']").click
+ # Wait for the picked tag to land in the trigger, then close the menu so it can't sit
+ # over the submit button on a slower runner.
+ find("[data-tag-select-target='selectionContainer']", text: tags(:one).name)
+ find("button[aria-label='Split tags']").click
+ assert_no_selector "[data-tag-select-target='menu']", visible: true
+ end
+
+ click_button "Update Rule"
+ end
+
+ assert_text "Rule updated", wait: 10
+
+ mine = JSON.parse(rule.reload.actions.sole.value)["splits"].first
+ assert_equal categories(:food_and_drink).id, mine["category_id"]
+ assert_equal merchant.id, mine["merchant_id"]
+ assert_equal [ tags(:one).id ], mine["tag_ids"]
+ end
+
test "creates a transaction rule through the modal with dynamically added condition and action" do
visit new_rule_path(resource_type: "transaction")
diff --git a/test/system/splits_test.rb b/test/system/splits_test.rb
new file mode 100644
index 0000000000..2c0fb525dd
--- /dev/null
+++ b/test/system/splits_test.rb
@@ -0,0 +1,71 @@
+require "application_system_test_case"
+
+class SplitsTest < ApplicationSystemTestCase
+ include EntriesTestHelper
+
+ setup do
+ sign_in @user = users(:family_admin)
+ @entry = create_transaction(amount: 100, name: "Split layout", account: accounts(:depository))
+ @entry.split!([ { name: "Groceries", amount: 70 }, { name: "Household", amount: 30 } ])
+ end
+
+ test "edit dialog keeps each split row's category, merchant and tag pickers inside the row" do
+ visit edit_transaction_split_path(@entry)
+
+ within "dialog" do
+ rows = all("[data-split-transaction-target='row']", minimum: 2)
+
+ rows.each do |row|
+ overflow = page.evaluate_script("arguments[0].scrollWidth - arguments[0].clientWidth", row)
+ assert_operator overflow, :<=, 0, "split row content overflows its row by #{overflow}px"
+ end
+ end
+ end
+
+ test "edit dialog saves the merchant and tags picked with the DS pickers" do
+ merchant = @user.family.merchants.create!(name: "Split Grocer")
+
+ visit edit_transaction_split_path(@entry)
+
+ within "dialog" do
+ within all("[data-split-transaction-target='row']", minimum: 2).first do
+ find("[data-merchant-select-target='button']").click
+ find("[role='option'][data-merchant-name='#{merchant.name}']").click
+ find("[data-tag-select-target='button']").click
+ find("[role='option'][data-tag-name='#{tags(:one).name}']").click
+ end
+
+ click_button I18n.t("splits.edit.submit")
+ end
+
+ assert_text I18n.t("splits.update.success")
+
+ child = @entry.reload.child_entries.find_by!(name: "Groceries")
+ assert_equal merchant.id, child.entryable.merchant_id
+ assert_equal [ tags(:one).id ], child.entryable.tag_ids
+ end
+
+ test "tag picker in a split row stays as tall as the other pickers" do
+ visit edit_transaction_split_path(@entry)
+
+ within "dialog" do
+ within all("[data-split-transaction-target='row']", minimum: 2).first do
+ assert_equal 1, picker_heights.uniq.size, "empty tag picker height differs: #{picker_heights}"
+
+ find("[data-tag-select-target='button']").click
+ find("[role='option'][data-tag-name='#{tags(:one).name}']").click
+ find("[data-tag-select-target='selectionContainer']", text: tags(:one).name)
+
+ assert_equal 1, picker_heights.uniq.size, "tag picker with a tag differs: #{picker_heights}"
+ end
+ end
+ end
+
+ private
+ # Heights of the category, merchant and tag fields in the current split row.
+ def picker_heights
+ evaluate_script(<<~JS, current_scope)
+ Array.from(arguments[0].querySelectorAll(".grid .form-field")).map((field) => Math.round(field.getBoundingClientRect().height))
+ JS
+ end
+end