Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feature: add categories structure lock/unlock toggle (#3987)

Anton9951b764dc07
diff --git a/app/components/DS/category_select.html.erb b/app/components/DS/category_select.html.erb
index 65cb0e996d..7413698605 100644
--- a/app/components/DS/category_select.html.erb
+++ b/app/components/DS/category_select.html.erb
@@ -4,6 +4,7 @@
data-category-select-default-color-value="<%= Category::COLORS.first %>"
data-category-select-disabled-value="<%= disabled %>"
data-category-select-auto-submit-value="<%= auto_submit %>"
+ data-category-select-locked-value="<%= locked %>"
data-category-select-create-label-value="<%= helpers.t("transactions.form.create_category", name: "__CATEGORY_NAME__") %>"
data-category-select-create-error-message-value="<%= helpers.t("transactions.form.create_category_error") %>"
data-category-select-parent-picker-label-value="<%= helpers.t("transactions.form.choose_parent", name: "__CATEGORY_NAME__") %>"
@@ -122,6 +123,9 @@
<p class="hidden px-3 py-1 text-xs text-destructive"
role="alert"
data-category-select-target="createError"></p>
+
+ <p class="hidden px-3 py-1 text-xs text-secondary"
+ data-category-select-target="emptyMessage"><%= helpers.t("transactions.form.no_matching_categories") %></p>
</div>
<%# Shown in place of the list after "Add as a subcategory…": pick a top-level parent. %>
diff --git a/app/components/DS/category_select.rb b/app/components/DS/category_select.rb
index c534ee82a5..f6d9296032 100644
--- a/app/components/DS/category_select.rb
+++ b/app/components/DS/category_select.rb
@@ -1,5 +1,5 @@
class DS::CategorySelect < DesignSystemComponent
- attr_reader :form, :categories, :selected_id, :disabled, :auto_submit, :blank_label
+ attr_reader :form, :categories, :selected_id, :disabled, :auto_submit, :blank_label, :locked
def initialize(
form:,
@@ -8,7 +8,8 @@ class DS::CategorySelect < DesignSystemComponent
selected_category: nil,
disabled: false,
auto_submit: false,
- blank_label: nil
+ blank_label: nil,
+ locked: false
)
@form = form
@categories = categories
@@ -17,6 +18,7 @@ class DS::CategorySelect < DesignSystemComponent
@disabled = disabled
@auto_submit = auto_submit
@blank_label = blank_label
+ @locked = locked
end
# A category shown as the selection without being one of `categories`,
diff --git a/app/controllers/api/v1/categories_controller.rb b/app/controllers/api/v1/categories_controller.rb
index 40ac1bf6cb..6654f42ec6 100644
--- a/app/controllers/api/v1/categories_controller.rb
+++ b/app/controllers/api/v1/categories_controller.rb
@@ -49,6 +49,14 @@ class Api::V1::CategoriesController < Api::V1::BaseController
def create
family = current_resource_owner.family
+
+ if family.categories_locked?
+ return render json: {
+ error: "unprocessable_entity",
+ message: "Categories are locked. Unlock them to add a new category."
+ }, status: :unprocessable_entity
+ end
+
attrs = category_params
if attrs[:parent_id].present? && !family.categories.exists?(id: attrs[:parent_id])
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb
index 57cac63a36..bbaaa13a77 100644
--- a/app/controllers/categories_controller.rb
+++ b/app/controllers/categories_controller.rb
@@ -3,6 +3,8 @@ class CategoriesController < ApplicationController
before_action :set_category, only: %i[edit update destroy]
before_action :set_categories, only: %i[update edit]
before_action :set_transaction, only: :create
+ before_action :require_admin!, only: :toggle_lock
+ before_action :ensure_categories_unlocked, only: %i[create bootstrap]
def index
@categories = Current.family.categories.alphabetically_by_hierarchy.to_a
@@ -16,6 +18,8 @@ class CategoriesController < ApplicationController
end
def new
+ return render :locked if Current.family.categories_locked?
+
@category = Current.family.categories.new color: Category::COLORS.sample
set_categories
end
@@ -101,6 +105,18 @@ class CategoriesController < ApplicationController
redirect_back_or_to categories_path, notice: t(".success")
end
+ def toggle_lock
+ locked = case params.require(:locked)
+ when true, "true" then true
+ when false, "false" then false
+ end
+ return head :bad_request if locked.nil?
+
+ Current.family.update!(categories_locked: locked)
+
+ redirect_back_or_to categories_path, notice: locked ? t(".locked") : t(".unlocked")
+ end
+
def perform_merge
permitted_params = category_merge_params
@@ -129,6 +145,29 @@ class CategoriesController < ApplicationController
@category = Current.family.categories.find(params[:id])
end
+ def ensure_categories_unlocked
+ return unless Current.family.categories_locked?
+
+ respond_to do |format|
+ format.html { redirect_back_or_to categories_path, alert: categories_locked_message }
+ format.turbo_stream { redirect_to categories_path, alert: categories_locked_message }
+ format.json { render json: { errors: categories_locked_errors }, status: :unprocessable_entity }
+ format.any { head :forbidden }
+ end
+ end
+
+ def categories_locked_message
+ if Current.user.admin?
+ t("categories.locked")
+ else
+ t("categories.index.locked_message")
+ end
+ end
+
+ def categories_locked_errors
+ [ categories_locked_message ]
+ end
+
def set_categories
@categories = unless @category.parent?
Current.family.categories.alphabetically.roots.where.not(id: @category.id)
diff --git a/app/javascript/controllers/category_select_controller.js b/app/javascript/controllers/category_select_controller.js
index 144a1a9569..1485762268 100644
--- a/app/javascript/controllers/category_select_controller.js
+++ b/app/javascript/controllers/category_select_controller.js
@@ -12,6 +12,7 @@ export default class extends Controller {
"createForm",
"createLabel",
"createError",
+ "emptyMessage",
"list",
"createAsSubcategory",
"parentPicker",
@@ -28,6 +29,7 @@ export default class extends Controller {
autoSubmit: Boolean,
createLabel: String,
createErrorMessage: String,
+ locked: Boolean,
parentPickerLabel: String,
};
@@ -70,21 +72,27 @@ export default class extends Controller {
const query = rawQuery.toLowerCase();
let exactMatch = false;
+ let anyVisible = false;
this.optionTargets.forEach((option) => {
const name = option.dataset.categoryName.toLowerCase();
const matches = name.includes(query);
option.classList.toggle("hidden", !matches);
+ if (matches) anyVisible = true;
if (name === query) exactMatch = true;
});
- const canCreate = rawQuery.length > 0 && !exactMatch;
+ const canCreate = !this.lockedValue && rawQuery.length > 0 && !exactMatch;
this.createFormTarget.classList.toggle("hidden", !canCreate);
this.createFormTarget.classList.toggle("flex", canCreate);
+ if (this.hasEmptyMessageTarget) {
+ this.emptyMessageTarget.classList.toggle("hidden", anyVisible || canCreate);
+ }
+
if (this.hasCreateAsSubcategoryTarget) {
// Nesting needs at least one top-level category to nest under.
const canNest = canCreate && this.parentOptionTargets.length > 0;
@@ -97,22 +105,40 @@ export default class extends Controller {
}
handleSearchKeydown(event) {
+ if (event.key !== "Enter") return;
+
+ // The search box sits inside the surrounding form, so Enter must never
+ // fall through and submit it.
+ event.preventDefault();
+
// With the parent picker open, Enter moves into it instead of creating a
- // top-level category (or submitting the surrounding form).
- if (event.key === "Enter" && this.#parentPickerOpen()) {
- event.preventDefault();
+ // top-level category.
+ if (this.#parentPickerOpen()) {
this.parentOptionTargets[0]?.focus();
return;
}
- if (
- event.key === "Enter" &&
- !this.createFormTarget.classList.contains("hidden") &&
- !this.creating
- ) {
- event.preventDefault();
- this.createCategory();
+ if (!this.createFormTarget.classList.contains("hidden")) {
+ if (!this.creating) this.createCategory();
+ return;
}
+
+ // Nothing to create (locked, or the name exists already): pick the match.
+ const query = this.searchTarget.value.trim().toLowerCase();
+ if (!query) return;
+
+ const visible = this.optionTargets.filter(
+ (option) => !option.classList.contains("hidden"),
+ );
+ const match =
+ visible.find(
+ (option) => option.dataset.categoryName.toLowerCase() === query,
+ ) ?? visible[0];
+ if (!match) return;
+
+ this.selectOption(match);
+ this.close();
+ this.submitForm();
}
// Escape from anywhere in the menu: leave the parent picker first, then
@@ -211,7 +237,7 @@ export default class extends Controller {
}
async #create(parentId) {
- if (this.creating) return;
+ if (this.creating || this.lockedValue) return;
const name = this.searchTarget.value.trim();
if (!name) return;
diff --git a/app/models/assistant/function/create_category.rb b/app/models/assistant/function/create_category.rb
index 8d1a6c76c2..380adbb8c2 100644
--- a/app/models/assistant/function/create_category.rb
+++ b/app/models/assistant/function/create_category.rb
@@ -47,6 +47,10 @@ class Assistant::Function::CreateCategory < Assistant::Function
end
def call(params = {})
+ if family.categories_locked?
+ return error("categories_locked", "Categories are locked. Unlock them before creating a new category.")
+ end
+
name = params["name"].to_s.strip
return error("name_required", "Please provide a name for the category.") if name.blank?
diff --git a/app/models/family.rb b/app/models/family.rb
index 2ff947e93f..564d24e9ae 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -254,6 +254,7 @@ class Family < ApplicationRecord
validates :default_account_sharing, inclusion: { in: SHARING_DEFAULTS }
validates :personal_budgets, inclusion: { in: [ true, false ] }
validates :household_budget_enabled, inclusion: { in: [ true, false ] }
+ validates :categories_locked, inclusion: { in: [ true, false ] }
validate :timezone_must_be_a_known_zone, if: :timezone_changed?
before_validation :normalize_enabled_currencies!
diff --git a/app/views/budget_categories/_no_categories.html.erb b/app/views/budget_categories/_no_categories.html.erb
index f785222891..b8d7a13ed7 100644
--- a/app/views/budget_categories/_no_categories.html.erb
+++ b/app/views/budget_categories/_no_categories.html.erb
@@ -5,7 +5,7 @@
<%= t(".no_categories_message") %>
</p>
- <% unless Current.user&.guest? %>
+ <% unless Current.family.categories_locked? || Current.user&.guest? %>
<div class="flex items-center gap-2">
<%= render DS::Button.new(
text: t(".use_defaults"),
diff --git a/app/views/categories/index.html.erb b/app/views/categories/index.html.erb
index 222f95e445..0de3efce41 100644
--- a/app/views/categories/index.html.erb
+++ b/app/views/categories/index.html.erb
@@ -2,6 +2,15 @@
<%= content_for :page_actions do %>
<% unless Current.user&.guest? %>
<%= render DS::Menu.new do |menu| %>
+ <% if Current.user.admin? %>
+ <% locked = Current.family.categories_locked? %>
+ <% menu.with_item(
+ variant: "button",
+ text: locked ? t(".unlock_categories") : t(".lock_categories"),
+ href: toggle_lock_categories_path(locked: !locked),
+ method: :patch,
+ icon: locked ? "lock-open" : "lock") %>
+ <% end %>
<% menu.with_item(
variant: "link",
text: t(".merge"),
@@ -17,17 +26,25 @@
confirm: CustomConfirm.for_resource_deletion("all categories", high_severity: true)) %>
<% end %>
- <%= render DS::Link.new(
- text: t(".new"),
- variant: "primary",
- icon: "plus",
- href: new_category_path,
- frame: :modal
- ) %>
+ <% unless Current.family.categories_locked? %>
+ <%= render DS::Link.new(
+ text: t(".new"),
+ variant: "primary",
+ icon: "plus",
+ href: new_category_path,
+ frame: :modal
+ ) %>
+ <% end %>
<% end %>
<% end %>
<div class="bg-container rounded-xl shadow-border-xs p-4">
+ <% if Current.family.categories_locked? %>
+ <div class="mb-4">
+ <%= render DS::Alert.new(message: t(".locked_message"), variant: :info) %>
+ </div>
+ <% end %>
+
<% if @categories.any? %>
<div class="space-y-4">
<%= render "categories/category_list_group",
@@ -41,7 +58,7 @@
<div class="flex justify-center items-center py-20">
<div class="text-center flex flex-col items-center max-w-[500px]">
<p class="text-sm text-secondary mb-4"><%= t(".empty") %></p>
- <% unless Current.user&.guest? %>
+ <% unless Current.family.categories_locked? || Current.user&.guest? %>
<div class="flex items-center gap-2">
<%= render DS::Button.new(
text: t(".bootstrap"),
diff --git a/app/views/categories/locked.html.erb b/app/views/categories/locked.html.erb
new file mode 100644
index 0000000000..a7579b5f94
--- /dev/null
+++ b/app/views/categories/locked.html.erb
@@ -0,0 +1,6 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t("categories.new.new_category")) %>
+ <% dialog.with_body do %>
+ <%= render DS::Alert.new(message: t("categories.index.locked_message"), variant: :info) %>
+ <% end %>
+<% end %>
diff --git a/app/views/category/dropdowns/show.html.erb b/app/views/category/dropdowns/show.html.erb
index b02cf0cb23..7fc3f4860c 100644
--- a/app/views/category/dropdowns/show.html.erb
+++ b/app/views/category/dropdowns/show.html.erb
@@ -1,7 +1,7 @@
<%= turbo_frame_tag "category_dropdown" do %>
<%# 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) && !Current.user&.guest? %>
+ <% can_create = can_annotate_account?(@transaction.entry.account) && !Current.family.categories_locked? && !Current.user&.guest? %>
<div class="flex flex-col relative"
data-controller="list-filter category-quick-create"
data-category-quick-create-create-url-value="<%= categories_path(format: :json) %>"
@@ -84,7 +84,7 @@
<div class="text-center flex flex-col items-center max-w-[500px]">
<p class="text-sm text-secondary font-normal mb-4"><%= t(".empty") %></p>
- <% unless Current.user&.guest? %>
+ <% unless Current.family.categories_locked? || Current.user&.guest? %>
<%= render DS::Button.new(
text: t(".bootstrap"),
variant: "outline",
diff --git a/app/views/transactions/_form.html.erb b/app/views/transactions/_form.html.erb
index 6f58e19f2b..bf54959ef8 100644
--- a/app/views/transactions/_form.html.erb
+++ b/app/views/transactions/_form.html.erb
@@ -44,7 +44,8 @@
form: ef,
categories: categories,
selected_id: ef.object.category_id,
- blank_label: t(".category_prompt")
+ blank_label: t(".category_prompt"),
+ locked: Current.family.categories_locked?
) %>
<% end %>
diff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erb
index 9238b41a58..09e0feb3c7 100644
--- a/app/views/transactions/show.html.erb
+++ b/app/views/transactions/show.html.erb
@@ -91,7 +91,8 @@
selected_id: ef.object.category_id,
disabled: @entry.split_child? || annotate_locked,
auto_submit: true,
- blank_label: t(".uncategorized")
+ blank_label: t(".uncategorized"),
+ locked: Current.family.categories_locked?
) %>
<% end %>
<% elsif @entry.transaction.category_set_on_transfer_outflow? %>
diff --git a/config/locales/views/categories/en.yml b/config/locales/views/categories/en.yml
index 7f985e4183..528619b24a 100644
--- a/config/locales/views/categories/en.yml
+++ b/config/locales/views/categories/en.yml
@@ -3,6 +3,10 @@ en:
categories:
bootstrap:
success: Default categories created successfully
+ locked: Categories are locked. Unlock them to add a new category.
+ toggle_lock:
+ locked: Categories locked
+ unlocked: Categories unlocked
category:
delete: Delete category
edit: Edit category
@@ -31,8 +35,11 @@ en:
categories_incomes: Income categories
delete_all: Delete all
empty: No categories found
+ lock_categories: Lock category creation
+ locked_message: Category creation is locked. Imports and bank syncs can still add categories.
merge: Merge categories
new: New category
+ unlock_categories: Unlock category creation
merge:
title: Merge categories
description: Select a target category and the categories to merge into it. Matching transactions and budget lines will move to the target.
diff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.yml
index fe1bc8d1be..c9cf987a79 100644
--- a/config/locales/views/transactions/en.yml
+++ b/config/locales/views/transactions/en.yml
@@ -51,6 +51,7 @@ en:
create_merchant: Create
create_merchant_error: Could not create merchant
merchant_search_placeholder: Search or create merchant
+ no_matching_categories: No matching categories
submit: Add transaction
tag_search_placeholder: Search or create tag
tags_label: Tags
diff --git a/config/routes.rb b/config/routes.rb
index ed0a070b59..69ca172238 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -442,6 +442,7 @@ Rails.application.routes.draw do
get :merge, on: :collection
post :perform_merge, on: :collection
post :bootstrap, on: :collection
+ patch :toggle_lock, on: :collection
delete :destroy_all, on: :collection
end
diff --git a/db/migrate/20261004120000_add_categories_locked_to_families.rb b/db/migrate/20261004120000_add_categories_locked_to_families.rb
new file mode 100644
index 0000000000..19cdafa81d
--- /dev/null
+++ b/db/migrate/20261004120000_add_categories_locked_to_families.rb
@@ -0,0 +1,5 @@
+class AddCategoriesLockedToFamilies < ActiveRecord::Migration[8.1]
+ def change
+ add_column :families, :categories_locked, :boolean, default: false, null: false
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index a0823baae4..f6c7ce4892 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -842,6 +842,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_15_090000) do
t.string "assistant_type", default: "builtin", null: false
t.boolean "auto_sync_on_login", default: true, null: false
t.string "bills_feed_token"
+ t.boolean "categories_locked", default: false, null: false
t.decimal "categorization_confidence_threshold", precision: 3, scale: 2, default: "0.7", null: false
t.string "categorization_provider", default: "llm", null: false
t.decimal "categorization_shadow_rate", precision: 3, scale: 2, default: "0.0", null: false
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 85dfe09d8d..ade0da102b 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -5694,7 +5694,7 @@ paths:
schema:
"$ref": "#/components/schemas/CategoryDetail"
'422':
- description: validation error - duplicate name
+ description: validation error - duplicate name or categories locked
content:
application/json:
schema:
diff --git a/spec/requests/api/v1/categories_spec.rb b/spec/requests/api/v1/categories_spec.rb
index e67802dc35..44a3a496e8 100644
--- a/spec/requests/api/v1/categories_spec.rb
+++ b/spec/requests/api/v1/categories_spec.rb
@@ -139,7 +139,7 @@ RSpec.describe 'API V1 Categories', type: :request do
run_test!
end
- response '422', 'validation error - duplicate name' do
+ response '422', 'validation error - duplicate name or categories locked' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) { { category: { name: parent_category.name } } }
diff --git a/test/controllers/api/v1/categories_controller_test.rb b/test/controllers/api/v1/categories_controller_test.rb
index 12d30fef89..a79e44e49d 100644
--- a/test/controllers/api/v1/categories_controller_test.rb
+++ b/test/controllers/api/v1/categories_controller_test.rb
@@ -286,6 +286,21 @@ class Api::V1::CategoriesControllerTest < ActionDispatch::IntegrationTest
assert_equal "bad_request", body["error"]
end
+ test "create returns 422 when categories are locked" do
+ @user.family.update!(categories_locked: true)
+
+ assert_no_difference "Category.count" do
+ post "/api/v1/categories",
+ params: { category: { name: "Locked Imported", color: "#22c55e", icon: "shapes" } },
+ headers: api_headers(read_write_api_key)
+ end
+
+ assert_response :unprocessable_entity
+ body = JSON.parse(response.body)
+ assert_equal "unprocessable_entity", body["error"]
+ assert body["message"].present?
+ end
+
private
def read_write_api_key
diff --git a/test/controllers/categories_controller_test.rb b/test/controllers/categories_controller_test.rb
index 53fae754ba..fe5c03d7bc 100644
--- a/test/controllers/categories_controller_test.rb
+++ b/test/controllers/categories_controller_test.rb
@@ -466,6 +466,106 @@ class CategoriesControllerTest < ActionDispatch::IntegrationTest
assert Category.exists?(other.id)
end
+ test "new renders a locked dialog when categories are locked" do
+ @family.update!(categories_locked: true)
+
+ get new_category_url
+
+ assert_response :success
+ assert_select "turbo-frame#modal dialog"
+ assert_match I18n.t("categories.index.locked_message"), response.body
+ end
+
+ test "create is blocked when categories are locked" do
+ @family.update!(categories_locked: true)
+
+ assert_no_difference "Category.count" do
+ post categories_url, params: {
+ category: { name: "Locked Out", color: Category::COLORS.sample } }
+ end
+
+ assert_redirected_to categories_url
+ end
+
+ test "create as json reports the locked error" do
+ @family.update!(categories_locked: true)
+
+ assert_no_difference "Category.count" do
+ post categories_url(format: :json), params: {
+ category: { name: "Locked Out", color: Category::COLORS.sample } }
+ end
+
+ assert_response :unprocessable_entity
+ assert_includes JSON.parse(response.body).fetch("errors"), I18n.t("categories.locked")
+ end
+
+ test "create as json shows members the lock explanation without the unlock instruction" do
+ @family.update!(categories_locked: true)
+ sign_in users(:family_member)
+
+ assert_no_difference "Category.count" do
+ post categories_url(format: :json), params: {
+ category: { name: "Locked Out", color: Category::COLORS.sample } }
+ end
+
+ assert_response :unprocessable_entity
+ errors = JSON.parse(response.body).fetch("errors")
+ assert_includes errors, I18n.t("categories.index.locked_message")
+ assert_not_includes errors, I18n.t("categories.locked")
+ end
+
+ test "bootstrap is blocked when categories are locked" do
+ @family.update!(categories_locked: true)
+
+ assert_no_difference "Category.count" do
+ post bootstrap_categories_url
+ end
+
+ assert_redirected_to categories_url
+ end
+
+ test "admin can lock and unlock categories" do
+ assert_not @family.categories_locked?
+
+ patch toggle_lock_categories_url(locked: true)
+
+ assert_redirected_to categories_url
+ assert @family.reload.categories_locked?
+
+ patch toggle_lock_categories_url(locked: false)
+
+ assert_not @family.reload.categories_locked?
+ end
+
+ test "locking twice keeps categories locked" do
+ patch toggle_lock_categories_url(locked: true)
+ patch toggle_lock_categories_url(locked: true)
+
+ assert @family.reload.categories_locked?
+ end
+
+ test "toggle_lock accepts a JSON boolean locked value" do
+ patch toggle_lock_categories_url, params: { locked: true }, as: :json
+
+ assert @family.reload.categories_locked?
+ end
+
+ test "toggle_lock rejects a non-boolean locked value" do
+ patch toggle_lock_categories_url, params: { locked: "banana" }
+
+ assert_response :bad_request
+ assert_not @family.reload.categories_locked?
+ end
+
+ test "non-admin cannot toggle the category lock" do
+ sign_in users(:family_member)
+
+ patch toggle_lock_categories_url(locked: true)
+
+ assert_redirected_to accounts_url
+ assert_not @family.reload.categories_locked?
+ end
+
private
def capture_sql_queries
queries = []
diff --git a/test/models/assistant/function/create_category_test.rb b/test/models/assistant/function/create_category_test.rb
index 059ca05be8..0d6c0efb66 100644
--- a/test/models/assistant/function/create_category_test.rb
+++ b/test/models/assistant/function/create_category_test.rb
@@ -112,6 +112,17 @@ class Assistant::Function::CreateCategoryTest < ActiveSupport::TestCase
assert_equal "validation_failed", result[:error]
end
+ test "soft error when categories are locked" do
+ @family.update!(categories_locked: true)
+
+ assert_no_difference "@family.categories.count" do
+ result = @fn.call("name" => "Locked Category")
+
+ assert_equal false, result[:success]
+ assert_equal "categories_locked", result[:error]
+ end
+ end
+
test "cannot use a parent from another family" do
other_family = Family.create!(name: "Other", currency: "USD", locale: "en", country: "US", timezone: "UTC")
other_parent = other_family.categories.create!(name: "Foreign Parent", color: "#e99537", lucide_icon: "shapes")
diff --git a/test/models/category_import_test.rb b/test/models/category_import_test.rb
index 92128bd222..f9945d3565 100644
--- a/test/models/category_import_test.rb
+++ b/test/models/category_import_test.rb
@@ -92,4 +92,24 @@ class CategoryImportTest < ActiveSupport::TestCase
error = assert_raises(ActiveRecord::RecordInvalid) { import.generate_rows_from_csv }
assert_includes error.message, "Missing required columns: name"
end
+
+ test "imports categories even when the family is locked" do
+ @family.update!(categories_locked: true)
+
+ csv = <<~CSV
+ name,color,parent_category,icon
+ Locked Root,#f97316,,house
+ Locked Child,#407706,Locked Root,plug
+ CSV
+
+ import = @family.imports.create!(type: "CategoryImport", raw_file_str: csv, col_sep: ",")
+ import.generate_rows_from_csv
+
+ assert_difference -> { @family.categories.count }, 2 do
+ import.send(:import!)
+ end
+
+ assert_equal Category.find_by!(family: @family, name: "Locked Root"),
+ Category.find_by!(family: @family, name: "Locked Child").parent
+ end
end
diff --git a/test/models/import/category_mapping_test.rb b/test/models/import/category_mapping_test.rb
index 11ee50be26..90e152dcc1 100644
--- a/test/models/import/category_mapping_test.rb
+++ b/test/models/import/category_mapping_test.rb
@@ -102,4 +102,18 @@ class Import::CategoryMappingTest < ActiveSupport::TestCase
Import.where(id: ids).destroy_all
end
end
+
+ test "create_mappable! still creates categories when the family is locked" do
+ import = @mapping.import
+ import.family.update!(categories_locked: true)
+ name = "Locked Mapping #{SecureRandom.hex(4)}"
+
+ mapping = import.mappings.create!(key: name, create_when_empty: true, type: "Import::CategoryMapping")
+
+ assert_difference -> { import.family.categories.count }, 1 do
+ mapping.create_mappable!
+ end
+
+ assert import.family.categories.exists?(name: name)
+ end
end
diff --git a/test/system/categories_test.rb b/test/system/categories_test.rb
index e979ab62f5..8ff557772f 100644
--- a/test/system/categories_test.rb
+++ b/test/system/categories_test.rb
@@ -16,6 +16,19 @@ class CategoriesTest < ApplicationSystemTestCase
assert_text "My Shiny New Category"
end
+ test "locking categories hides in-app creation" do
+ visit categories_url
+
+ find("[data-DS--menu-target='button']", match: :first).click
+ click_button I18n.t("categories.index.lock_categories")
+
+ assert_text I18n.t("categories.index.locked_message")
+ assert_no_link I18n.t("categories.index.new")
+
+ find("[data-DS--menu-target='button']", match: :first).click
+ assert_button I18n.t("categories.index.unlock_categories")
+ end
+
test "trying to create a duplicate category fails" do
visit categories_url
click_link I18n.t("categories.new.new_category")
diff --git a/test/system/transaction_category_select_test.rb b/test/system/transaction_category_select_test.rb
index 4ec6527391..b9b421f082 100644
--- a/test/system/transaction_category_select_test.rb
+++ b/test/system/transaction_category_select_test.rb
@@ -158,6 +158,24 @@ class TransactionCategorySelectTest < ApplicationSystemTestCase
end
end
+ test "Enter in the category search picks the match while categories are locked" do
+ @user.family.update!(categories_locked: true)
+ visit new_transaction_url(account_id: accounts(:depository).id)
+ fill_in "entry[name]", with: "Locked picker"
+ find("input[name='entry[amount]']").set("12.34")
+
+ assert_no_difference "Entry.count" do
+ find("[data-controller='category-select'] button").click
+
+ within "[data-controller='category-select']" do
+ fill_in "Search categories", with: "Food"
+ find_field("Search categories").send_keys(:enter)
+
+ assert_selector "[data-category-select-target='selectionContainer']", text: "Food & Drink"
+ end
+ end
+ end
+
test "a new subcategory is listed under its parent straight away" do
parent = categories(:food_and_drink)
visit new_transaction_url