The personal finance app for everyone (by everyone)
Ruby
feat(transactions): create a category from the list's quick category picker (#3772)
scragnoge8e142db6342
diff --git a/app/components/DS/action_row.rb b/app/components/DS/action_row.rbnew file mode 100644index 0000000000..7a283f5a94--- /dev/null+++ b/app/components/DS/action_row.rb@@ -0,0 +1,43 @@+class DS::ActionRow < DesignSystemComponent+ # A full-width row button for actions inside pickers, dropdowns and lists:+ # `Create "Groceries"`, "Add as a subcategory…", "Back", or a pickable item+ # whose content (e.g. a category badge) is passed as the block.+ #+ # Rows reserve a fixed-width leading gutter (the icon slot) so their labels+ # line up with the list rows around them whether or not an icon is shown.+ #+ # - `tone: :primary` for the main action in a list, `:secondary` for+ # supporting ones.+ # - `hidden: true` renders it hidden (`hidden`, not `flex`); a Stimulus+ # controller reveals it by swapping those two classes.+ # - Any other options (`data:`, `aria:`, `title:`, `disabled:`) go on the+ # `<button>`.+ TONES = %i[primary secondary].freeze++ attr_reader :text, :icon, :tone, :hidden, :opts++ def initialize(text: nil, icon: nil, tone: :primary, hidden: false, **opts)+ @text = text+ @icon = icon+ @tone = TONES.include?(tone.to_sym) ? tone.to_sym : :primary+ @hidden = hidden+ @opts = opts+ end++ def classes+ class_names(+ "items-center gap-1.5 w-full rounded-lg px-2 py-1.5 text-sm text-left cursor-pointer",+ "hover:bg-container-inset-hover focus-ring disabled:opacity-50 disabled:cursor-not-allowed",+ tone == :primary ? "font-medium text-primary" : "text-secondary",+ hidden ? "hidden" : "flex",+ opts[:class]+ )+ end++ erb_template <<~ERB+ <%= content_tag :button, type: "button", class: classes, **opts.except(:class) do %>+ <span class="flex items-center justify-center w-5 h-5 shrink-0"><%= helpers.icon(icon, size: "sm", color: "current") if icon %></span>+ <% if content? %><%= content %><% else %><span class="min-w-0 truncate"><%= text %></span><% end %>+ <% end %>+ ERB+enddiff --git a/app/components/DS/category_select.html.erb b/app/components/DS/category_select.html.erbindex a2095419d1..a33f0db561 100644--- a/app/components/DS/category_select.html.erb+++ b/app/components/DS/category_select.html.erb@@ -99,13 +99,13 @@<% end %><% end %>- <button type="button"- class="hidden text-primary text-sm cursor-pointer items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-container-inset-hover"- data-category-select-target="createForm"- data-action="click->category-select#createCategory">- <%= helpers.icon("plus") %>+ <%= render DS::ActionRow.new(+ icon: "plus",+ hidden: true,+ data: { category_select_target: "createForm", action: "click->category-select#createCategory" }+ ) do %><span data-category-select-target="createLabel"></span>- </button>+ <% end %><p class="hidden px-3 py-1 text-xs text-destructive"data-category-select-target="createError"></p>diff --git a/app/javascript/controllers/category_quick_create_controller.js b/app/javascript/controllers/category_quick_create_controller.jsnew file mode 100644index 0000000000..430c063457--- /dev/null+++ b/app/javascript/controllers/category_quick_create_controller.js@@ -0,0 +1,241 @@+import { Controller } from "@hotwired/stimulus";+import { createCategory } from "utils/category_create";++// Lets the transaction list's quick category picker create a category that+// doesn't exist yet, optionally under a top-level parent. The new category is+// assigned by submitting the same update form a normal row uses, so the row+// refreshes in place and the "create a rule?" prompt still appears.+//+// The create targets are only rendered when the user may annotate the+// account; without them this controller does nothing.+export default class extends Controller {+ static targets = [+ "input",+ "createButton",+ "createLabel",+ "assignForm",+ "categoryIdField",+ "error",+ "list",+ "createAsSubcategory",+ "parentPicker",+ "parentPickerLabel",+ ];++ static values = {+ createUrl: String,+ color: String,+ labelTemplate: String,+ errorMessage: String,+ assignErrorMessage: String,+ existingNames: Array,+ parentPickerLabel: String,+ };++ connect() {+ this.onAssignEnd = (event) => this.#assignFinished(event);+ this.onFrameMissing = (event) => this.#assignResponseMissing(event);+ this.frame = this.element.closest("turbo-frame");++ if (this.hasAssignFormTarget) {+ this.assignFormTarget.addEventListener(+ "turbo:submit-end",+ this.onAssignEnd,+ );+ }+ this.frame?.addEventListener("turbo:frame-missing", this.onFrameMissing);+ this.update();+ }++ disconnect() {+ if (this.hasAssignFormTarget) {+ this.assignFormTarget.removeEventListener(+ "turbo:submit-end",+ this.onAssignEnd,+ );+ }+ this.frame?.removeEventListener("turbo:frame-missing", this.onFrameMissing);+ }++ update() {+ if (!this.hasCreateButtonTarget) return;++ // Editing the name returns to the list, so the picker never shows a stale name.+ this.hideParentPicker();++ const name = this.inputTarget.value.trim();+ const canCreate = name.length > 0 && !this.#nameExists(name);++ this.#toggle(this.createButtonTarget, canCreate);+ if (this.hasCreateAsSubcategoryTarget) {+ this.#toggle(this.createAsSubcategoryTarget, canCreate);+ }++ if (canCreate) {+ this.createLabelTarget.textContent = this.labelTemplateValue.replace(+ "__NAME__",+ name,+ );+ // list-filter shows "No categories found" when nothing matches; with a+ // create option on offer that reads as a contradiction, so hide it.+ this.element+ .querySelector("[data-list-filter-target='emptyMessage']")+ ?.classList.add("hidden");+ }++ this.#clearError();+ }++ // Enter creates only when the search matches no row at all; otherwise+ // list-filter keeps handling Enter to pick the highlighted row.+ createOnEnter(event) {+ if (!this.hasCreateButtonTarget) return;+ if (this.createButtonTarget.classList.contains("hidden")) return;+ if (this.#parentPickerOpen || this.#hasVisibleRows) return;++ event.preventDefault();+ this.create();+ }++ showParentPicker(event) {+ event?.preventDefault();+ if (!this.hasParentPickerTarget) return;++ const name = this.inputTarget.value.trim();+ if (!name) return;++ this.parentPickerLabelTarget.textContent =+ this.parentPickerLabelValue.replace("__NAME__", name);++ this.listTarget.classList.add("hidden");+ this.#toggle(this.parentPickerTarget, true);+ }++ hideParentPicker(event) {+ event?.preventDefault();+ if (!this.hasParentPickerTarget) return;++ this.#toggle(this.parentPickerTarget, false);+ this.listTarget.classList.remove("hidden");+ }++ createUnderParent(event) {+ event.preventDefault();+ this.create(event.currentTarget.dataset.parentId);+ }++ // Called directly as an action (receives an Event) or with a parent id.+ async create(parentIdOrEvent = null) {+ if (this.creating || !this.hasCreateButtonTarget) return;+ const parentId =+ typeof parentIdOrEvent === "string" ? parentIdOrEvent : null;++ const name = this.inputTarget.value.trim();+ if (!name) return;++ this.creating = true;+ this.createButtonTarget.disabled = true;+ this.#clearError();++ try {+ // A retry after a failed assignment reuses the category created the+ // first time; posting it again would fail as a duplicate name.+ let category = this.#createdCategory(name, parentId);+ if (!category) {+ const result = await createCategory({+ url: this.createUrlValue,+ name,+ color: this.colorValue,+ parentId,+ });+ category = result.category;++ if (!category) {+ this.hideParentPicker();+ this.#showError(result.error || this.errorMessageValue);+ return;+ }+ this.created = { name, parentId, id: category.id };+ }++ this.categoryIdFieldTarget.value = category.id;+ this.assigning = true;+ this.assignFormTarget.requestSubmit();+ } finally {+ this.creating = false;+ this.createButtonTarget.disabled = false;+ }+ }++ // The category exists once create succeeds; if the assignment then fails+ // (network, session, permission) say so rather than failing silently.+ #assignFinished(event) {+ const failed = this.assigning && !event.detail?.success;+ this.assigning = false;+ if (!failed) return;++ this.hideParentPicker();+ this.#showError(this.assignErrorMessageValue);+ }++ // An error or redirect response has no matching frame, so Turbo would swap+ // the picker for its generic "Content missing" message. Keep the picker and+ // explain what happened instead.+ #assignResponseMissing(event) {+ if (!this.assigning) return;++ event.preventDefault();+ this.assigning = false;+ this.hideParentPicker();+ this.#showError(this.assignErrorMessageValue);+ }++ // Only the same choice (name and parent) is a retry; choosing a different+ // parent for that name is a new create, which the server then validates.+ #createdCategory(name, parentId) {+ if (+ this.created?.name.toLocaleLowerCase() !== name.toLocaleLowerCase() ||+ this.created.parentId !== parentId+ ) {+ return null;+ }+ return { id: this.created.id };+ }++ #nameExists(name) {+ const wanted = name.toLocaleLowerCase();+ return this.existingNamesValue.some(+ (existing) => existing.toLocaleLowerCase() === wanted,+ );+ }++ get #parentPickerOpen() {+ return (+ this.hasParentPickerTarget &&+ !this.parentPickerTarget.classList.contains("hidden")+ );+ }++ get #hasVisibleRows() {+ return Array.from(this.element.querySelectorAll(".filterable-item")).some(+ (item) => item.style.display !== "none" && item.offsetParent !== null,+ );+ }++ #toggle(element, visible) {+ element.classList.toggle("hidden", !visible);+ element.classList.toggle("flex", visible);+ }++ #showError(message) {+ this.errorTarget.textContent = message;+ this.errorTarget.classList.remove("hidden");+ }++ #clearError() {+ if (!this.hasErrorTarget) return;++ this.errorTarget.textContent = "";+ this.errorTarget.classList.add("hidden");+ }+}diff --git a/app/javascript/controllers/category_select_controller.js b/app/javascript/controllers/category_select_controller.jsindex 90e80bc286..efc4f59dd3 100644--- a/app/javascript/controllers/category_select_controller.js+++ b/app/javascript/controllers/category_select_controller.js@@ -1,4 +1,5 @@import { Controller } from "@hotwired/stimulus";+import { createCategory } from "utils/category_create";export default class extends Controller {static targets = [@@ -147,38 +148,21 @@ export default class extends Controller {this.clearCreateError();try {- const response = await fetch(this.createUrlValue, {- method: "POST",- headers: {- Accept: "application/json",- "Content-Type": "application/json",- "X-CSRF-Token": this.csrfToken,- },- body: JSON.stringify({- category: {- name,- color: this.defaultColorValue,- },- }),+ const { category, error } = await createCategory({+ url: this.createUrlValue,+ name,+ color: this.defaultColorValue,});- const category = await response.json();-- if (!response.ok) {- this.showCreateError(- category.errors?.join(", ") || category.error,- );+ if (!category) {+ this.showCreateError(error);return;}- this.createFormTarget.insertAdjacentHTML(- "beforebegin",- category.html,- );+ this.createFormTarget.insertAdjacentHTML("beforebegin", category.html);const newOption = this.optionTargets.find(- (option) =>- option.dataset.categoryId === String(category.id),+ (option) => option.dataset.categoryId === String(category.id),);if (newOption) this.selectOption(newOption);@@ -187,8 +171,6 @@ export default class extends Controller {this.filter();this.close();this.submitForm();- } catch {- this.showCreateError();} finally {this.creating = false;this.createFormTarget.disabled = false;@@ -219,10 +201,4 @@ export default class extends Controller {this.createErrorTarget.classList.remove("hidden");}-- get csrfToken() {- return document- .querySelector('meta[name="csrf-token"]')- ?.getAttribute("content");- }}diff --git a/app/javascript/utils/category_create.js b/app/javascript/utils/category_create.jsnew file mode 100644index 0000000000..07f94ba058--- /dev/null+++ b/app/javascript/utils/category_create.js@@ -0,0 +1,40 @@+// Creates a category through the categories JSON endpoint. Shared by the+// category pickers (DS::CategorySelect and the transaction list's quick+// picker) so both send the same request and read errors the same way.+//+// Resolves to { category } on success, or { error } on failure, where `error`+// is the server's message when it sent one (null means "use your default").+export async function createCategory({ url, name, color, parentId = null }) {+ try {+ const response = await fetch(url, {+ method: "POST",+ headers: {+ Accept: "application/json",+ "Content-Type": "application/json",+ "X-CSRF-Token": csrfToken(),+ },+ body: JSON.stringify({+ category: {+ name,+ color,+ ...(parentId ? { parent_id: parentId } : {}),+ },+ }),+ });+ const body = await response.json().catch(() => ({}));++ if (!response.ok || !body.id) return { error: errorMessage(body) };++ return { category: body };+ } catch {+ return { error: null };+ }+}++function errorMessage(body) {+ return body.errors?.join(", ") || body.error || body.message || null;+}++function csrfToken() {+ return document.querySelector('meta[name="csrf-token"]')?.content;+}diff --git a/app/views/category/dropdowns/show.html.erb b/app/views/category/dropdowns/show.html.erbindex b514dc1082..6973ac52d6 100644--- a/app/views/category/dropdowns/show.html.erb+++ b/app/views/category/dropdowns/show.html.erb@@ -1,5 +1,16 @@<%= turbo_frame_tag "category_dropdown" do %>- <div class="flex flex-col relative" data-controller="list-filter">+ <%# Creating is only offered where the category can then be assigned: a user who %>+ <%# can't annotate this account would get a new category the assignment then rejects. %>+ <% can_create = can_annotate_account?(@transaction.entry.account) %>+ <div class="flex flex-col relative"+ data-controller="list-filter category-quick-create"+ data-category-quick-create-create-url-value="<%= categories_path(format: :json) %>"+ data-category-quick-create-color-value="<%= Category::COLORS.sample %>"+ data-category-quick-create-label-template-value="<%= t(".create", name: "__NAME__") %>"+ data-category-quick-create-error-message-value="<%= t(".create_error") %>"+ data-category-quick-create-assign-error-message-value="<%= t(".assign_error") %>"+ data-category-quick-create-parent-picker-label-value="<%= t(".choose_parent", name: "__NAME__") %>"+ data-category-quick-create-existing-names-value="<%= @categories.map(&:name).to_json %>"><div class="grow p-1.5"><div class="relative flex items-center bg-container border border-secondary rounded-lg"><input@@ -12,14 +23,45 @@aria-autocomplete="list"class="bg-container placeholder:text-sm placeholder:text-secondary font-normal h-10 relative pl-10 w-full border-none rounded-lg focus:outline-hidden focus:ring-0"data-list-filter-target="input"- data-action="list-filter#filter keydown->list-filter#handleKeydown">+ data-category-quick-create-target="input"+ data-action="list-filter#filter category-quick-create#update keydown->list-filter#handleKeydown keydown.enter->category-quick-create#createOnEnter"><%= icon("search", class: "absolute inset-0 ml-2 transform top-1/2 -translate-y-1/2") %></div></div>- <div data-list-filter-target="list" role="listbox" class="flex flex-col gap-0.5 p-1.5 mt-0.5 mr-2 max-h-64 overflow-y-scroll scrollbar">+ <% parent_options = can_create ? @categories.select { |category| category.parent_id.nil? }.sort_by { |category| category.name.downcase } : [] %>+ <div data-list-filter-target="list" data-category-quick-create-target="list" role="listbox" class="flex flex-col gap-0.5 p-1.5 mt-0.5 mr-2 max-h-64 overflow-y-scroll scrollbar"><div class="pb-2 pl-4 mr-2 text-secondary hidden" data-list-filter-target="emptyMessage"><%= t(".no_categories") %></div>+ <% if can_create %>+ <%# Shown by category-quick-create when the search matches no existing category name. %>+ <%# Creating goes through the same update form as picking a row, so the list row %>+ <%# refreshes and the "create a rule?" prompt still appears. %>+ <%= form_with url: transaction_category_path(@transaction.entry, grouped: params[:grouped]),+ method: :patch,+ data: { turbo_frame: "category_dropdown", category_quick_create_target: "assignForm" } do |f| %>+ <%= hidden_field_tag "entry[entryable_type]", "Transaction", id: nil %>+ <%= hidden_field_tag "entry[entryable_attributes][id]", @transaction.id, id: nil %>+ <%= hidden_field_tag "entry[entryable_attributes][category_id]", nil, id: nil, data: { category_quick_create_target: "categoryIdField" } %>+ <% end %>+ <%= render DS::ActionRow.new(+ icon: "plus",+ hidden: true,+ data: { category_quick_create_target: "createButton", action: "category-quick-create#create" }+ ) do %>+ <span data-category-quick-create-target="createLabel"></span>+ <% end %>+ <% if parent_options.any? %>+ <%= render DS::ActionRow.new(+ text: t(".create_as_subcategory"),+ icon: "corner-down-right",+ tone: :secondary,+ hidden: true,+ data: { category_quick_create_target: "createAsSubcategory", action: "category-quick-create#showParentPicker" }+ ) %>+ <% end %>+ <p class="hidden px-2 pb-1 text-xs text-destructive" role="alert" data-category-quick-create-target="error"></p>+ <% end %><% if @recent_categories.any? %><div data-list-filter-target="recentSection"><p class="pl-2 pb-1 text-xs font-medium text-secondary uppercase tracking-wide"><%= t(".recent") %></p>@@ -53,6 +95,26 @@<% end %></div>+ <%# Shown in place of the list after "Add as a subcategory…". Only top-level %>+ <%# categories can be parents (categories are at most two levels deep). %>+ <% if parent_options.any? %>+ <div class="hidden flex-col gap-0.5 p-1.5 mt-0.5 mr-2 max-h-64 overflow-y-scroll scrollbar"+ data-category-quick-create-target="parentPicker">+ <p class="px-2 pb-1 text-xs text-secondary" data-category-quick-create-target="parentPickerLabel"></p>+ <% parent_options.each do |parent| %>+ <%= render DS::ActionRow.new(tone: :secondary, data: { parent_id: parent.id, action: "category-quick-create#createUnderParent" }) do %>+ <%= render partial: "categories/badge", locals: { category: parent } %>+ <% end %>+ <% end %>+ <%= render DS::ActionRow.new(+ text: t(".back"),+ icon: "arrow-left",+ tone: :secondary,+ data: { action: "category-quick-create#hideParentPicker" }+ ) %>+ </div>+ <% end %>+<%= render "shared/ruler", classes: "my-2" %><div class="relative p-1.5 w-full">diff --git a/config/locales/views/category/dropdowns/en.yml b/config/locales/views/category/dropdowns/en.ymlindex f384041cd6..1989e7ac8c 100644--- a/config/locales/views/category/dropdowns/en.yml+++ b/config/locales/views/category/dropdowns/en.yml@@ -6,7 +6,13 @@ en:delete: Delete categoryedit: Edit categoryshow:+ assign_error: Created the category but couldn't assign it. Choose Create again to retry.+ back: Back+ choose_parent: 'Create "%{name}" under:'clear: Clear category+ create: Create "%{name}"+ create_as_subcategory: Add as a subcategory…+ create_error: Couldn't create that category. Please try again.no_categories: No categories foundrecent: Recentsearch_placeholder: Searchdiff --git a/test/components/DS/action_row_test.rb b/test/components/DS/action_row_test.rbnew file mode 100644index 0000000000..cd4f503462--- /dev/null+++ b/test/components/DS/action_row_test.rb@@ -0,0 +1,40 @@+require "test_helper"++class DS::ActionRowTest < ViewComponent::TestCase+ test "renders a full-width row button with an icon gutter and label" do+ render_inline(DS::ActionRow.new(text: "Create category", icon: "plus"))++ assert_selector "button[type=button].flex.w-full", text: "Create category"+ assert_selector "button > span:first-child svg"+ end++ test "keeps the gutter without an icon so labels align" do+ render_inline(DS::ActionRow.new(text: "Back"))++ assert_selector "button > span:first-child.w-5"+ assert_no_selector "button svg"+ end++ test "hidden renders hidden instead of flex, for Stimulus to reveal" do+ render_inline(DS::ActionRow.new(text: "Create", hidden: true))++ assert_selector "button.hidden", visible: :all+ assert_no_selector "button.flex", visible: :all+ end++ test "tone sets emphasis and unknown tones fall back to primary" do+ render_inline(DS::ActionRow.new(text: "Supporting", tone: :secondary))+ assert_selector "button.text-secondary"++ render_inline(DS::ActionRow.new(text: "Main", tone: :bogus))+ assert_selector "button.font-medium.text-primary"+ end++ test "block content replaces the text label and extra options reach the button" do+ render_inline(DS::ActionRow.new(data: { action: "picker#choose", parent_id: "42" }, aria: { label: "Choose parent" })) do+ "<span class='badge'>Shopping</span>".html_safe+ end++ assert_selector "button[data-action='picker#choose'][data-parent-id='42'][aria-label='Choose parent'] span.badge", text: "Shopping"+ end+enddiff --git a/test/components/previews/action_row_component_preview.rb b/test/components/previews/action_row_component_preview.rbnew file mode 100644index 0000000000..18369f98c4--- /dev/null+++ b/test/components/previews/action_row_component_preview.rb@@ -0,0 +1,13 @@+class ActionRowComponentPreview < ViewComponent::Preview+ # @param tone select {{ DS::ActionRow::TONES }}+ # @param icon select ["plus", "corner-down-right", "arrow-left", ""]+ def default(tone: :primary, icon: "plus")+ render DS::ActionRow.new(text: 'Create "Groceries"', icon: icon.presence, tone: tone)+ end++ # How rows stack inside a picker: a primary action, a supporting action and a+ # "back" row share the same gutter as the list's own rows.+ def picker_actions+ render_with_template+ end+enddiff --git a/test/components/previews/action_row_component_preview/picker_actions.html.erb b/test/components/previews/action_row_component_preview/picker_actions.html.erbnew file mode 100644index 0000000000..c4d4d2681c--- /dev/null+++ b/test/components/previews/action_row_component_preview/picker_actions.html.erb@@ -0,0 +1,5 @@+<div class="w-64 p-1.5 bg-container rounded-lg shadow-border-xs">+ <%= render DS::ActionRow.new(text: 'Create "Groceries"', icon: "plus") %>+ <%= render DS::ActionRow.new(text: "Add as a subcategory…", icon: "corner-down-right", tone: :secondary) %>+ <%= render DS::ActionRow.new(text: "Back", icon: "arrow-left", tone: :secondary) %>+</div>diff --git a/test/controllers/category/dropdowns_controller_test.rb b/test/controllers/category/dropdowns_controller_test.rbindex d8e1eb61f4..6f3741c0e7 100644--- a/test/controllers/category/dropdowns_controller_test.rb+++ b/test/controllers/category/dropdowns_controller_test.rb@@ -2,6 +2,7 @@ require "test_helper"class Category::DropdownsControllerTest < ActionDispatch::IntegrationTestinclude ActionView::RecordIdentifier+ include EntriesTestHelpersetup dosign_in users(:family_admin)@@ -47,4 +48,47 @@ class Category::DropdownsControllerTest < ActionDispatch::IntegrationTestassert_response :successassert_select "[data-list-filter-target='recentSection']", falseend++ test "renders a hidden create option wired to assign the new category to this transaction" do+ get category_dropdown_url(transaction_id: @transaction.id)++ assert_response :success+ assert_select "[data-controller~='category-quick-create'][data-category-quick-create-create-url-value=?]", categories_path(format: :json)+ assert_select "button.hidden[data-category-quick-create-target='createButton']"+ assert_select "form[data-category-quick-create-target='assignForm'][action=?]", transaction_category_path(@transaction.entry) do+ assert_select "input[name='entry[entryable_attributes][id]'][value=?]", @transaction.id.to_s+ assert_select "input[name='entry[entryable_attributes][category_id]'][data-category-quick-create-target='categoryIdField']"+ end+ end++ test "passes existing category names so the create option hides on an exact match" do+ get category_dropdown_url(transaction_id: @transaction.id)++ assert_response :success+ names_attr = css_select("[data-controller~='category-quick-create']").first["data-category-quick-create-existing-names-value"]+ assert_includes JSON.parse(names_attr), categories(:food_and_drink).name+ end++ test "offers only top-level categories as parents for a new subcategory" do+ get category_dropdown_url(transaction_id: @transaction.id)++ assert_response :success+ assert_select "button.hidden[data-category-quick-create-target='createAsSubcategory']"+ assert_select "[data-category-quick-create-target='parentPicker']" do+ assert_select "button[data-parent-id=?]", categories(:food_and_drink).id+ assert_select "button[data-parent-id=?]", categories(:subcategory).id, count: 0+ end+ end++ test "does not offer creating a category on an account the user can only view" do+ sign_in users(:family_member)+ entry = create_transaction(account: accounts(:credit_card), name: "Read-only card spend")++ get category_dropdown_url(transaction_id: entry.entryable.id)++ assert_response :success+ assert_select "[data-category-quick-create-target='createButton']", count: 0+ assert_select "[data-category-quick-create-target='createAsSubcategory']", count: 0+ assert_select "[data-category-quick-create-target='parentPicker']", count: 0+ endenddiff --git a/test/system/transaction_quick_category_create_test.rb b/test/system/transaction_quick_category_create_test.rbnew file mode 100644index 0000000000..dda075725b--- /dev/null+++ b/test/system/transaction_quick_category_create_test.rb@@ -0,0 +1,174 @@+require "application_system_test_case"++class TransactionQuickCategoryCreateTest < ApplicationSystemTestCase+ include ActionView::RecordIdentifier+ include EntriesTestHelper++ setup do+ sign_in @user = users(:family_admin)+ @entry = @user.family.entries.transactions.order(date: :desc).first+ page.current_window.resize_to(1280, 900)+ end++ test "creates a new category from the list's quick picker and assigns it" do+ visit transactions_url++ within "##{dom_id(@entry.entryable, 'category_menu_desktop')}" do+ find("button", match: :first).click+ end++ assert_difference "Category.count", +1 do+ within "turbo-frame#category_dropdown" do+ find("input[type='search']").fill_in with: "Quick Picker Category"+ click_button 'Create "Quick Picker Category"'+ end++ # The update response re-renders the row's category menu with the new category.+ assert_selector "##{dom_id(@entry.entryable, 'category_menu_desktop')} [data-testid='category-name']", text: "Quick Picker Category"+ end++ category = @user.family.categories.find_by!(name: "Quick Picker Category")+ assert_equal category.id, @entry.entryable.reload.category_id+ end++ test "hides the create option when the search exactly matches an existing category" do+ existing = @user.family.categories.alphabetically.first++ visit transactions_url++ within "##{dom_id(@entry.entryable, 'category_menu_desktop')}" do+ find("button", match: :first).click+ end++ within "turbo-frame#category_dropdown" do+ find("input[type='search']").fill_in with: existing.name.upcase+ assert_no_button "Create \"#{existing.name.upcase}\""+ end+ end++ test "creates a new subcategory from the list's quick picker and assigns it" do+ parent = categories(:food_and_drink)+ visit transactions_url++ within "##{dom_id(@entry.entryable, 'category_menu_desktop')}" do+ find("button", match: :first).click+ end++ assert_difference "Category.count", +1 do+ within "turbo-frame#category_dropdown" do+ find("input[type='search']").fill_in with: "Quick Picker Subcategory"+ click_button "Add as a subcategory…"+ assert_text 'Create "Quick Picker Subcategory" under:'+ find("button[data-parent-id='#{parent.id}']").click+ end++ assert_selector "##{dom_id(@entry.entryable, 'category_menu_desktop')} [data-testid='category-name']", text: "Quick Picker Subcategory"+ end++ category = @user.family.categories.find_by!(name: "Quick Picker Subcategory")+ assert_equal parent, category.parent+ assert_equal category.id, @entry.entryable.reload.category_id+ end++ test "back from the quick picker's parent list returns to the category list" do+ visit transactions_url++ within "##{dom_id(@entry.entryable, 'category_menu_desktop')}" do+ find("button", match: :first).click+ end++ within "turbo-frame#category_dropdown" do+ find("input[type='search']").fill_in with: "Changed My Mind"+ click_button "Add as a subcategory…"+ assert_selector "[data-category-quick-create-target='parentPicker']", visible: true++ click_button "Back"+ assert_no_selector "[data-category-quick-create-target='parentPicker']", visible: true+ assert_button 'Create "Changed My Mind"'+ end+ end++ test "hides 'No categories found' while the create option is showing" do+ visit transactions_url+ open_quick_picker++ within "turbo-frame#category_dropdown" do+ find("input[type='search']").fill_in with: "Nothing Matches This"+ assert_button 'Create "Nothing Matches This"'+ assert_no_text "No categories found"+ end+ end++ test "reports a failed assignment after the category was created" do+ visit transactions_url+ open_quick_picker+ assert_selector "turbo-frame#category_dropdown input[type='search']"++ # Let the create request through but block the assign request in the+ # browser, so it fails at the network level with no response to act on.+ browser = page.driver.browser+ browser.execute_cdp("Network.enable")+ browser.execute_cdp("Network.setBlockedURLs", urls: [ "*/transactions/*/category*" ])++ within "turbo-frame#category_dropdown" do+ find("input[type='search']").fill_in with: "Created But Not Assigned"+ click_button 'Create "Created But Not Assigned"'+ assert_selector "[data-category-quick-create-target='error']", text: "couldn't assign it"+ end++ assert @user.family.categories.exists?(name: "Created But Not Assigned")+ assert_not_equal "Created But Not Assigned", @entry.entryable.reload.category&.name++ # Retrying assigns the category created the first time instead of+ # posting a duplicate.+ browser.execute_cdp("Network.setBlockedURLs", urls: [])+ within "turbo-frame#category_dropdown" do+ click_button 'Create "Created But Not Assigned"'+ end++ assert_selector "##{dom_id(@entry.entryable, 'category_menu_desktop')} [data-testid='category-name']", text: "Created But Not Assigned"+ assert_equal 1, @user.family.categories.where(name: "Created But Not Assigned").count+ assert_equal "Created But Not Assigned", @entry.entryable.reload.category&.name+ ensure+ page.driver.browser.execute_cdp("Network.setBlockedURLs", urls: [])+ end++ test "choosing a parent after a failed assignment does not reuse the top-level category" do+ parent = categories(:food_and_drink)+ visit transactions_url+ open_quick_picker+ assert_selector "turbo-frame#category_dropdown input[type='search']"++ browser = page.driver.browser+ browser.execute_cdp("Network.enable")+ browser.execute_cdp("Network.setBlockedURLs", urls: [ "*/transactions/*/category*" ])++ within "turbo-frame#category_dropdown" do+ find("input[type='search']").fill_in with: "Top Level First"+ click_button 'Create "Top Level First"'+ assert_selector "[data-category-quick-create-target='error']", text: "couldn't assign it"+ end++ # A different choice for the same name is a new create, which the server+ # rejects as a duplicate, instead of assigning the top-level category.+ browser.execute_cdp("Network.setBlockedURLs", urls: [])+ within "turbo-frame#category_dropdown" do+ click_button "Add as a subcategory…"+ find("button[data-parent-id='#{parent.id}']").click+ assert_selector "[data-category-quick-create-target='error']", text: /taken/i+ end++ assert_equal 1, @user.family.categories.where(name: "Top Level First").count+ assert_nil @user.family.categories.find_by(name: "Top Level First").parent+ assert_not_equal "Top Level First", @entry.entryable.reload.category&.name+ ensure+ page.driver.browser.execute_cdp("Network.setBlockedURLs", urls: [])+ end++ private+ def open_quick_picker+ within "##{dom_id(@entry.entryable, 'category_menu_desktop')}" do+ find("button", match: :first).click+ end+ end+end