The personal finance app for everyone (by everyone)
Ruby
fix(merchants): preserve user-selected merchant colors on save (#2760) (#2802)
Erkan Doğan71106f63b05a
diff --git a/app/models/family_merchant.rb b/app/models/family_merchant.rbindex 3baec76bb4..d45947aca6 100644--- a/app/models/family_merchant.rb+++ b/app/models/family_merchant.rb@@ -6,12 +6,16 @@ class FamilyMerchant < Merchantbefore_validation :set_default_colorbefore_save :generate_logo_url_from_website, if: :should_generate_logo?- validates :color, presence: true+ validates :color, presence: true, format: { with: /\A#[0-9A-Fa-f]{6}\z/ }validates :name, uniqueness: { scope: :family }privatedef set_default_color- self.color = COLORS.sample+ self.color = COLORS.sample unless valid_hex_color?+ end++ def valid_hex_color?+ color.present? && color.match?(/\A#[0-9A-Fa-f]{6}\z/)enddef should_generate_logo?diff --git a/test/controllers/family_merchants_controller_test.rb b/test/controllers/family_merchants_controller_test.rbindex b5dc950b3d..16ee04f757 100644--- a/test/controllers/family_merchants_controller_test.rb+++ b/test/controllers/family_merchants_controller_test.rb@@ -22,11 +22,14 @@ class FamilyMerchantsControllerTest < ActionDispatch::IntegrationTestendassert_redirected_to family_merchants_path+ created_merchant = FamilyMerchant.find_by(name: "new merchant")+ assert_equal "#000000", created_merchant.colorendtest "should update merchant" dopatch family_merchant_url(@merchant), params: { family_merchant: { name: "new name", color: "#000000" } }assert_redirected_to family_merchants_path+ assert_equal "#000000", @merchant.reload.colorendtest "should destroy merchant" dodiff --git a/test/models/family_merchant_test.rb b/test/models/family_merchant_test.rbnew file mode 100644index 0000000000..c100af2a3c--- /dev/null+++ b/test/models/family_merchant_test.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++require "test_helper"++class FamilyMerchantTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ end++ test "preserves user-selected color on creation" do+ merchant = FamilyMerchant.create!(+ family: @family,+ name: "Custom Color Merchant",+ color: "#123456"+ )++ assert_equal "#123456", merchant.color+ end++ test "sets random default color when color is blank" do+ merchant = FamilyMerchant.create!(+ family: @family,+ name: "Default Color Merchant"+ )++ assert_includes FamilyMerchant::COLORS, merchant.color+ end++ test "preserves existing color on update" do+ merchant = FamilyMerchant.create!(+ family: @family,+ name: "Original Merchant",+ color: "#123456"+ )++ merchant.update!(name: "Renamed Merchant")+ assert_equal "#123456", merchant.reload.color+ end++ test "replaces invalid hex color with default sample" do+ merchant = FamilyMerchant.create!(+ family: @family,+ name: "Invalid Color Merchant",+ color: "invalid-color"+ )++ assert_includes FamilyMerchant::COLORS, merchant.color+ end+end