From 321d4e1648342542820eb9c61db2cb31c2f024da Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 13:21:31 +0000 Subject: [PATCH 1/3] Store pinned, administrative and smtp_enabled as timestamps Replaces the articles.pinned, groups.administrative and mail_aliases.smtp_enabled booleans with pinned_at, administrative_at and smtp_enabled_at, so we also know since when a flag is set (#436). A TimestampFlag concern keeps the boolean model interface and the API attributes, filters and sorting unchanged. The migration backfills the timestamps from paper_trail versions where possible. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiPSKHKsyFrdS5JjrHUVLg --- app/models/article.rb | 5 +- app/models/concerns/timestamp_flag.rb | 43 +++++++++++++ app/models/group.rb | 5 +- app/models/mail_alias.rb | 5 +- app/resources/v1/application_resource.rb | 19 ++++++ app/resources/v1/article_resource.rb | 3 +- app/resources/v1/group_resource.rb | 4 +- app/resources/v1/mail_alias_resource.rb | 3 +- ...0_replace_boolean_flags_with_timestamps.rb | 37 +++++++++++ db/schema.rb | 8 +-- spec/models/article_spec.rb | 6 -- spec/models/concerns/timestamp_flag_spec.rb | 63 +++++++++++++++++++ spec/models/group_spec.rb | 6 -- .../v1/groups_controller/index_spec.rb | 26 ++++++++ .../v1/groups_controller/update_spec.rb | 4 +- ...with_conditionally_updatable_attributes.rb | 11 +++- 16 files changed, 220 insertions(+), 28 deletions(-) create mode 100644 app/models/concerns/timestamp_flag.rb create mode 100644 db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb create mode 100644 spec/models/concerns/timestamp_flag_spec.rb diff --git a/app/models/article.rb b/app/models/article.rb index 5e3ccce5..f59a6499 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -1,4 +1,6 @@ class Article < ApplicationRecord + include TimestampFlag + mount_base64_uploader :cover_photo, CoverPhotoUploader has_paper_trail skip: [:cover_photo] @@ -10,12 +12,11 @@ class Article < ApplicationRecord validates :title, presence: true validates :content, presence: true validates :publicly_visible, inclusion: [true, false] - validates :pinned, inclusion: [true, false] validate :only_one_pinned_article scope :publicly_visible, -> { where(publicly_visible: true) } - scope :pinned, -> { where(pinned: true) } + timestamp_flag :pinned def owners if group.present? diff --git a/app/models/concerns/timestamp_flag.rb b/app/models/concerns/timestamp_flag.rb new file mode 100644 index 00000000..960e96e2 --- /dev/null +++ b/app/models/concerns/timestamp_flag.rb @@ -0,0 +1,43 @@ +# Stores a yes/no flag as a nullable timestamp, so we also know since when it was set +# (see https://github.com/csvalpha/amber-api/issues/436). +# +# timestamp_flag :pinned +# +# reads and writes the `pinned_at` column, but keeps the boolean interface the rest of the +# app and the API use: `pinned`, `pinned?`, `pinned = true`, `saved_change_to_pinned?` and +# the scopes `pinned` / `not_pinned`. Setting the flag to true again keeps the original +# timestamp, setting it to false (or nil) clears it. +module TimestampFlag + extend ActiveSupport::Concern + + class_methods do + def timestamp_flag(name, column: :"#{name}_at") + scope name, -> { where.not(column => nil) } + scope :"not_#{name}", -> { where(column => nil) } + + define_timestamp_flag_accessors(name, column) + define_method(:"saved_change_to_#{name}?") { public_send(:"saved_change_to_#{column}?") } + define_method(:"#{name}_changed?") { public_send(:"#{column}_changed?") } + end + + # Filters records on a timestamp flag, accepting the values a JSON:API filter or a boolean + # gives (e.g. ['true'], 'false', true) + def where_timestamp_flag(name, value) + values = Array(value).map { |v| ActiveModel::Type::Boolean.new.cast(v) }.uniq + return all if values.size != 1 + + values.first ? public_send(name) : public_send(:"not_#{name}") + end + + private + + def define_timestamp_flag_accessors(name, column) + define_method(name) { self[column].present? } + alias_method :"#{name}?", name + + define_method(:"#{name}=") do |value| + self[column] = (self[column] || Time.zone.now if ActiveModel::Type::Boolean.new.cast(value)) + end + end + end +end diff --git a/app/models/group.rb b/app/models/group.rb index 7d941543..a1f49b61 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -1,4 +1,6 @@ class Group < ApplicationRecord + include TimestampFlag + mount_base64_uploader :avatar, AvatarUploader has_paper_trail skip: [:avatar] @@ -22,8 +24,9 @@ class Group < ApplicationRecord .where(memberships: { user_id: user.id }) } + timestamp_flag :administrative + validates :name, presence: true - validates :administrative, inclusion: [true, false] validates :kind, presence: true, inclusion: { in: %w[bestuur commissie dispuut genootschap groep huis kiemgroep werkgroep kring lichting curiositas zal] diff --git a/app/models/mail_alias.rb b/app/models/mail_alias.rb index 3f120fed..3322e2c8 100644 --- a/app/models/mail_alias.rb +++ b/app/models/mail_alias.rb @@ -1,12 +1,15 @@ class MailAlias < ApplicationRecord + include TimestampFlag + has_paper_trail belongs_to :group, optional: true belongs_to :user, optional: true belongs_to :moderator_group, class_name: 'Group', optional: true + timestamp_flag :smtp_enabled + validates :email, presence: true, uniqueness: true validates :moderation_type, inclusion: %w[open semi_moderated moderated] - validates :smtp_enabled, inclusion: [true, false] validate :group_xor_user? validate :known_mail_domain? validate :when_moderated_with_moderator? diff --git a/app/resources/v1/application_resource.rb b/app/resources/v1/application_resource.rb index 90b2b347..962245d3 100644 --- a/app/resources/v1/application_resource.rb +++ b/app/resources/v1/application_resource.rb @@ -8,6 +8,25 @@ class V1::ApplicationResource < JSONAPI::Resource filter :search + class_attribute :_timestamp_flags, instance_writer: false, default: {} + + # Exposes a model's TimestampFlag as a boolean attribute that can be filtered and sorted on + def self.timestamp_flag_attribute(name, column: :"#{name}_at") + self._timestamp_flags = _timestamp_flags.merge(name.to_s => column) + attribute name + filter name, apply: ->(records, value, _options) { records.where_timestamp_flag(name, value) } + end + + def self.apply_sort(records, order_options, context = {}) + flags, others = order_options.partition { |field, _| _timestamp_flags.key?(field.to_s) } + records = super(records, others.to_h, context) + flags.each do |field, direction| + column = records.arel_table[_timestamp_flags[field.to_s]] + records = records.order(column.not_eq(nil).public_send(direction)) + end + records + end + # simplecov:disable def self.creatable_fields(_context) [] diff --git a/app/resources/v1/article_resource.rb b/app/resources/v1/article_resource.rb index a582a94d..1f8601ba 100644 --- a/app/resources/v1/article_resource.rb +++ b/app/resources/v1/article_resource.rb @@ -1,6 +1,7 @@ class V1::ArticleResource < V1::ApplicationResource attributes :title, :content, :publicly_visible, :content_camofied, :cover_photo, - :amount_of_comments, :cover_photo_url, :author_name, :avatar_thumb_url, :pinned + :amount_of_comments, :cover_photo_url, :author_name, :avatar_thumb_url + timestamp_flag_attribute :pinned def amount_of_comments @model.comments.size diff --git a/app/resources/v1/group_resource.rb b/app/resources/v1/group_resource.rb index 976e5fd6..6ec6cc0a 100644 --- a/app/resources/v1/group_resource.rb +++ b/app/resources/v1/group_resource.rb @@ -1,6 +1,7 @@ class V1::GroupResource < V1::ApplicationResource attributes :name, :avatar_url, :avatar_thumb_url, :description, :description_camofied, - :kind, :recognized_at_gma, :rejected_at_gma, :administrative, :avatar + :kind, :recognized_at_gma, :rejected_at_gma, :avatar + timestamp_flag_attribute :administrative def avatar_url @model.avatar.url @@ -22,7 +23,6 @@ def description_camofied filter :active, apply: ->(records, _value, _options) { records.active } filter :kind - filter :administrative def fetchable_fields return super - [:avatar] if current_user diff --git a/app/resources/v1/mail_alias_resource.rb b/app/resources/v1/mail_alias_resource.rb index 3c31f077..553c9822 100644 --- a/app/resources/v1/mail_alias_resource.rb +++ b/app/resources/v1/mail_alias_resource.rb @@ -1,5 +1,6 @@ class V1::MailAliasResource < V1::ApplicationResource - attributes :email, :moderation_type, :description, :smtp_enabled, :last_received_at + attributes :email, :moderation_type, :description, :last_received_at + timestamp_flag_attribute :smtp_enabled has_one :group, always_include_linkage_data: true has_one :user, always_include_linkage_data: true diff --git a/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb b/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb new file mode 100644 index 00000000..64692c58 --- /dev/null +++ b/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb @@ -0,0 +1,37 @@ +# Stores articles.pinned, groups.administrative and mail_aliases.smtp_enabled as timestamps, so we +# also know since when they were set (see https://github.com/csvalpha/amber-api/issues/436). +class ReplaceBooleanFlagsWithTimestamps < ActiveRecord::Migration[7.2] + FLAGS = [ + %w[articles Article pinned], + %w[groups Group administrative], + %w[mail_aliases MailAlias smtp_enabled] + ].freeze + + def up + FLAGS.each do |table, item_type, flag| + add_column table, :"#{flag}_at", :datetime + + # The flag was set at the last version that turned it on, which paper_trail stored in + # object_changes. Records without such a version had it from the start. + execute <<~SQL.squish + UPDATE #{table} SET #{flag}_at = COALESCE( + (SELECT MAX(versions.created_at) FROM versions + WHERE versions.item_type = '#{item_type}' AND versions.item_id = #{table}.id + AND versions.object_changes -> '#{flag}' ->> 1 = 'true'), + #{table}.created_at + ) + WHERE #{table}.#{flag} = TRUE + SQL + + remove_column table, flag + end + end + + def down + FLAGS.each do |table, _item_type, flag| + add_column table, flag, :boolean, default: false, null: false + execute "UPDATE #{table} SET #{flag} = TRUE WHERE #{flag}_at IS NOT NULL" + remove_column table, :"#{flag}_at" + end + end +end diff --git a/db/schema.rb b/db/schema.rb index f666c72d..aab0343b 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.2].define(version: 2026_12_01_120000) do +ActiveRecord::Schema[7.2].define(version: 2026_12_03_120000) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -106,7 +106,7 @@ t.integer "author_id" t.string "cover_photo" t.integer "comments_count", default: 0, null: false - t.boolean "pinned", default: false, null: false + t.datetime "pinned_at" t.index ["author_id"], name: "index_articles_on_author_id" t.index ["deleted_at"], name: "index_articles_on_deleted_at" t.index ["group_id"], name: "index_articles_on_group_id" @@ -320,7 +320,7 @@ t.string "recognized_at_gma" t.string "rejected_at_gma" t.string "avatar" - t.boolean "administrative", default: false, null: false + t.datetime "administrative_at" t.index ["deleted_at"], name: "index_groups_on_deleted_at" end @@ -345,8 +345,8 @@ t.datetime "updated_at", precision: nil, null: false t.datetime "deleted_at", precision: nil t.bigint "moderator_group_id" - t.boolean "smtp_enabled", default: false, null: false t.datetime "last_received_at", precision: nil + t.datetime "smtp_enabled_at" t.index ["email"], name: "index_mail_aliases_on_email", unique: true t.index ["moderator_group_id"], name: "index_mail_aliases_on_moderator_group_id" end diff --git a/spec/models/article_spec.rb b/spec/models/article_spec.rb index a6dcad18..9efb696a 100644 --- a/spec/models/article_spec.rb +++ b/spec/models/article_spec.rb @@ -35,12 +35,6 @@ it { expect(article).not_to be_valid } end - - context 'when without pinned' do - subject(:article) { build(:article, pinned: nil) } - - it { expect(article).not_to be_valid } - end end describe '#save' do diff --git a/spec/models/concerns/timestamp_flag_spec.rb b/spec/models/concerns/timestamp_flag_spec.rb new file mode 100644 index 00000000..66e6fd07 --- /dev/null +++ b/spec/models/concerns/timestamp_flag_spec.rb @@ -0,0 +1,63 @@ +require 'rails_helper' + +RSpec.describe TimestampFlag do + # Article stores its pinned flag in pinned_at + subject(:article) { build(:article) } + + describe 'setting the flag' do + it { expect(article.pinned).to be false } + + context 'when set to true' do + before { article.pinned = true } + + it { expect(article.pinned?).to be true } + it { expect(article.pinned_at).to be_within(1.minute).of(Time.zone.now) } + end + + context 'when set to a string from the API' do + before { article.pinned = 'true' } + + it { expect(article.pinned?).to be true } + end + + context 'when set to true while already set' do + subject(:article) { build(:article, pinned_at: 1.year.ago) } + + it { expect { article.pinned = true }.not_to(change(article, :pinned_at)) } + end + + context 'when set to false or nil' do + subject(:article) { build(:article, pinned_at: 1.year.ago) } + + it { expect { article.pinned = false }.to change(article, :pinned_at).to(nil) } + it { expect { article.pinned = nil }.to change(article, :pinned).to(false) } + end + end + + describe 'change tracking' do + subject(:article) { create(:article) } + + it { expect { article.pinned = true }.to change(article, :pinned_changed?).to(true) } + + it do + article.update!(pinned: true) + expect(article.saved_change_to_pinned?).to be true + end + + it do + article.update!(pinned: false) + expect(article.saved_change_to_pinned?).to be false + end + end + + describe 'scopes' do + let!(:pinned) { create(:article, pinned: true) } + let!(:unpinned) { create(:article, pinned: false) } + + it { expect(Article.pinned).to contain_exactly(pinned) } + it { expect(Article.not_pinned).to contain_exactly(unpinned) } + it { expect(Article.where_timestamp_flag(:pinned, ['true'])).to contain_exactly(pinned) } + it { expect(Article.where_timestamp_flag(:pinned, 'false')).to contain_exactly(unpinned) } + it { expect(Article.where_timestamp_flag(:pinned, %w[true false]).count).to eq 2 } + end +end diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb index 59b32538..c21be187 100644 --- a/spec/models/group_spec.rb +++ b/spec/models/group_spec.rb @@ -12,12 +12,6 @@ it { expect(group).not_to be_valid } end - context 'when without administrative' do - subject(:group) { build_stubbed(:group, administrative: nil) } - - it { expect(group).not_to be_valid } - end - context 'when without a kind' do subject(:group) { build_stubbed(:group, kind: nil) } diff --git a/spec/requests/v1/groups_controller/index_spec.rb b/spec/requests/v1/groups_controller/index_spec.rb index efd5cf00..4ea21440 100644 --- a/spec/requests/v1/groups_controller/index_spec.rb +++ b/spec/requests/v1/groups_controller/index_spec.rb @@ -56,5 +56,31 @@ it { expect(json_object_ids).not_to include(records[0].id) } it { expect(json_object_ids).not_to include(records[1].id) } end + + describe 'sorting on administrative' do + include_context 'when authenticated' do + let(:user) { create(:user, user_permission_list: [record_permission]) } + end + + let(:administrative_group) { create(:group, administrative: true) } + let(:other_group) { create(:group, administrative: false) } + + before do + administrative_group + other_group + end + + context 'when descending' do + subject(:request) { get("#{record_url}?sort=-administrative") } + + it { expect(json_object_ids.index(administrative_group.id)).to be < json_object_ids.index(other_group.id) } + end + + context 'when ascending' do + subject(:request) { get("#{record_url}?sort=administrative") } + + it { expect(json_object_ids.index(administrative_group.id)).to be > json_object_ids.index(other_group.id) } + end + end end end diff --git a/spec/requests/v1/groups_controller/update_spec.rb b/spec/requests/v1/groups_controller/update_spec.rb index ca0d5ea1..19030a56 100644 --- a/spec/requests/v1/groups_controller/update_spec.rb +++ b/spec/requests/v1/groups_controller/update_spec.rb @@ -20,7 +20,9 @@ %i[name recognized_at_gma rejected_at_gma administrative], :ok do let(:record) { create(:group) } let(:record_url) { "/v1/groups/#{record.id}" } - let(:override_attrs) { { kind: attributes_for(:group)[:kind] } } + let(:override_attrs) do + { kind: attributes_for(:group)[:kind], administrative: !record.administrative } + end let(:record_permission) { 'group.update' } before do diff --git a/spec/support/behaviors/requests/model_with_conditionally_updatable_attributes.rb b/spec/support/behaviors/requests/model_with_conditionally_updatable_attributes.rb index 462a01b4..e23f1295 100644 --- a/spec/support/behaviors/requests/model_with_conditionally_updatable_attributes.rb +++ b/spec/support/behaviors/requests/model_with_conditionally_updatable_attributes.rb @@ -25,17 +25,22 @@ }) end + # Reads a database column, or a virtual attribute such as a TimestampFlag + def attribute_value(record, attribute) + record.has_attribute?(attribute) ? record[attribute] : record.public_send(attribute) + end + describe 'when without permission' do before { request && record.reload } it_behaves_like response == :ok ? '200 OK' : '204 No Content' unrestricted_attrs.each do |attribute| - it { expect(record[attribute]).to eq(new_attrs[attribute]) } + it { expect(attribute_value(record, attribute)).to eq(new_attrs[attribute]) } end permissible_attrs.each do |attribute| - it { expect(record[attribute]).not_to eq(new_attrs[attribute]) } + it { expect(attribute_value(record, attribute)).not_to eq(new_attrs[attribute]) } end end @@ -49,7 +54,7 @@ it_behaves_like response == :ok ? '200 OK' : '204 No Content' (unrestricted_attrs + permissible_attrs).each do |attribute| - it { expect(record[attribute]).to eq(new_attrs[attribute]) } + it { expect(attribute_value(record, attribute)).to eq(new_attrs[attribute]) } end end end From c297de3a8ab5460763592256a8916aa56e5431bf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 13:36:40 +0000 Subject: [PATCH 2/3] Store privacy consents and setup_complete as timestamps Converts users.ifes_data_sharing_preference, info_in_almanak and allow_sofia_sharing to *_consented_at, and setup_complete to setup_completed_at, so we know when a user gave consent (#436). The API and the user import keep their boolean fields. Also addresses review feedback: change tracking now follows the boolean rather than the timestamp, toggling a flag off and on keeps its original timestamp, and sorting keeps the order of mixed sort fields. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiPSKHKsyFrdS5JjrHUVLg --- app/controllers/v1/users_controller.rb | 13 ++++++--- app/models/concerns/timestamp_flag.rb | 27 ++++++++++++++----- app/models/user.rb | 9 ++++++- app/resources/v1/application_resource.rb | 18 +++++++------ app/resources/v1/group_resource.rb | 2 +- app/resources/v1/user_resource.rb | 9 ++++--- ...0_replace_boolean_flags_with_timestamps.rb | 26 ++++++++++-------- db/schema.rb | 8 +++--- spec/models/concerns/timestamp_flag_spec.rb | 20 ++++++++++++++ spec/models/import/user_spec.rb | 2 +- .../v1/groups_controller/index_spec.rb | 9 +++++++ .../v1/users_controller/update_spec.rb | 4 ++- 12 files changed, 106 insertions(+), 41 deletions(-) diff --git a/app/controllers/v1/users_controller.rb b/app/controllers/v1/users_controller.rb index 2f242e68..710f9a74 100644 --- a/app/controllers/v1/users_controller.rb +++ b/app/controllers/v1/users_controller.rb @@ -97,8 +97,7 @@ def batch_import # rubocop:disable Metrics/AbcSize return render json: { errors: import.errors }, status: :unprocessable_entity unless import.valid? import.save!(live_run) - render json: { users: import.imported_users.to_json(except: excluded_display_properties), - errors: import.errors } + render json: { users: imported_users_json(import), errors: import.errors } end def context @@ -107,10 +106,16 @@ def context private + def imported_users_json(import) + import.imported_users.to_json(except: excluded_display_properties, + methods: %i[ifes_data_sharing_preference info_in_almanak]) + end + def excluded_display_properties %i[created_at updated_at deleted_at activated_at archived_at password_digest activation_token - avatar activation_token_valid_till setup_complete otp_secret_key otp_required - ical_secret_key ical_categories id] + avatar activation_token_valid_till setup_completed_at otp_secret_key otp_required + ical_secret_key ical_categories id ifes_data_sharing_consented_at + info_in_almanak_consented_at sofia_sharing_consented_at] end def otp_already_required_error diff --git a/app/models/concerns/timestamp_flag.rb b/app/models/concerns/timestamp_flag.rb index 960e96e2..cd3c1f09 100644 --- a/app/models/concerns/timestamp_flag.rb +++ b/app/models/concerns/timestamp_flag.rb @@ -4,20 +4,19 @@ # timestamp_flag :pinned # # reads and writes the `pinned_at` column, but keeps the boolean interface the rest of the -# app and the API use: `pinned`, `pinned?`, `pinned = true`, `saved_change_to_pinned?` and -# the scopes `pinned` / `not_pinned`. Setting the flag to true again keeps the original -# timestamp, setting it to false (or nil) clears it. +# app and the API use: `pinned`, `pinned?`, `pinned = true`, `pinned_changed?(from:, to:)`, +# `saved_change_to_pinned?` and the scopes `pinned` / `not_pinned`. Setting the flag to true +# again keeps the original timestamp, setting it to false (or nil) clears it. module TimestampFlag extend ActiveSupport::Concern - class_methods do + class_methods do # rubocop:disable Metrics/BlockLength def timestamp_flag(name, column: :"#{name}_at") scope name, -> { where.not(column => nil) } scope :"not_#{name}", -> { where(column => nil) } define_timestamp_flag_accessors(name, column) - define_method(:"saved_change_to_#{name}?") { public_send(:"saved_change_to_#{column}?") } - define_method(:"#{name}_changed?") { public_send(:"#{column}_changed?") } + define_timestamp_flag_change_tracking(name, column) end # Filters records on a timestamp flag, accepting the values a JSON:API filter or a boolean @@ -36,7 +35,21 @@ def define_timestamp_flag_accessors(name, column) alias_method :"#{name}?", name define_method(:"#{name}=") do |value| - self[column] = (self[column] || Time.zone.now if ActiveModel::Type::Boolean.new.cast(value)) + self[column] = if ActiveModel::Type::Boolean.new.cast(value) + self[column] || attribute_in_database(column) || Time.zone.now + end + end + end + + def define_timestamp_flag_change_tracking(name, column) + define_method(:"saved_change_to_#{name}?") do + before, after = saved_change_to_attribute(column) + before.present? != after.present? + end + define_method(:"#{name}_changed?") do |**options| + was = attribute_in_database(column).present? + now = public_send(name) + was != now && options.fetch(:from, was) == was && options.fetch(:to, now) == now end end end diff --git a/app/models/user.rb b/app/models/user.rb index 5fef4999..39e03f21 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,6 +1,8 @@ require 'csv' class User < ApplicationRecord # rubocop:disable Metrics/ClassLength + include TimestampFlag + has_one_time_password mount_base64_uploader :avatar, AvatarUploader @@ -79,7 +81,12 @@ class User < ApplicationRecord # rubocop:disable Metrics/ClassLength after_commit :sync_mail_aliases scope :activated, -> { where(activated_at: ...Time.zone.now) } - scope :sofia_users, -> { where(allow_sofia_sharing: true) } + timestamp_flag :ifes_data_sharing_preference, column: :ifes_data_sharing_consented_at + timestamp_flag :info_in_almanak, column: :info_in_almanak_consented_at + timestamp_flag :allow_sofia_sharing, column: :sofia_sharing_consented_at + timestamp_flag :setup_complete, column: :setup_completed_at + + scope :sofia_users, -> { allow_sofia_sharing } scope :login_enabled, -> { where(login_enabled: true) } scope :sidekiq_access, -> { where(sidekiq_access: true) } scope :birthday, lambda { |month = Time.zone.now.month, day = Time.zone.now.day| diff --git a/app/resources/v1/application_resource.rb b/app/resources/v1/application_resource.rb index 962245d3..35eb36f3 100644 --- a/app/resources/v1/application_resource.rb +++ b/app/resources/v1/application_resource.rb @@ -10,21 +10,23 @@ class V1::ApplicationResource < JSONAPI::Resource class_attribute :_timestamp_flags, instance_writer: false, default: {} - # Exposes a model's TimestampFlag as a boolean attribute that can be filtered and sorted on - def self.timestamp_flag_attribute(name, column: :"#{name}_at") + # Exposes a model's TimestampFlag as a boolean attribute that can be sorted (and optionally + # filtered) on + def self.timestamp_flag_attribute(name, column: :"#{name}_at", filter: false) self._timestamp_flags = _timestamp_flags.merge(name.to_s => column) attribute name + return unless filter + filter name, apply: ->(records, value, _options) { records.where_timestamp_flag(name, value) } end def self.apply_sort(records, order_options, context = {}) - flags, others = order_options.partition { |field, _| _timestamp_flags.key?(field.to_s) } - records = super(records, others.to_h, context) - flags.each do |field, direction| - column = records.arel_table[_timestamp_flags[field.to_s]] - records = records.order(column.not_eq(nil).public_send(direction)) + order_options.reduce(records) do |sorted, (field, direction)| + column = _timestamp_flags[field.to_s] + next super(sorted, { field => direction }, context) unless column + + sorted.order(sorted.arel_table[column].not_eq(nil).public_send(direction)) end - records end # simplecov:disable diff --git a/app/resources/v1/group_resource.rb b/app/resources/v1/group_resource.rb index 6ec6cc0a..99344731 100644 --- a/app/resources/v1/group_resource.rb +++ b/app/resources/v1/group_resource.rb @@ -1,7 +1,7 @@ class V1::GroupResource < V1::ApplicationResource attributes :name, :avatar_url, :avatar_thumb_url, :description, :description_camofied, :kind, :recognized_at_gma, :rejected_at_gma, :avatar - timestamp_flag_attribute :administrative + timestamp_flag_attribute :administrative, filter: true def avatar_url @model.avatar.url diff --git a/app/resources/v1/user_resource.rb b/app/resources/v1/user_resource.rb index cc5dc867..a214358a 100644 --- a/app/resources/v1/user_resource.rb +++ b/app/resources/v1/user_resource.rb @@ -1,13 +1,16 @@ class V1::UserResource < V1::ApplicationResource # rubocop:disable Metrics/ClassLength attributes :username, :first_name, :last_name_prefix, :last_name, :full_name, :nickname, :login_enabled, :otp_required, :activated_at, :emergency_contact, :emergency_number, - :ifes_data_sharing_preference, :info_in_almanak, :almanak_subscription_preference, + :almanak_subscription_preference, :digtus_subscription_preference, :email, :birthday, :address, :postcode, :city, :phone_number, :food_preferences, :vegetarian, :study, :start_study, :picture_publication_preference, :ical_secret_key, :ical_categories, :password, :avatar, :avatar_url, :avatar_thumb_url, - :user_details_sharing_preference, :allow_sofia_sharing, :trailer_drivers_license, - :sidekiq_access, :setup_complete + :user_details_sharing_preference, :trailer_drivers_license, :sidekiq_access + timestamp_flag_attribute :ifes_data_sharing_preference, column: :ifes_data_sharing_consented_at + timestamp_flag_attribute :info_in_almanak, column: :info_in_almanak_consented_at + timestamp_flag_attribute :allow_sofia_sharing, column: :sofia_sharing_consented_at + timestamp_flag_attribute :setup_complete, column: :setup_completed_at def avatar_url @model.avatar.url diff --git a/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb b/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb index 64692c58..bb15dbae 100644 --- a/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb +++ b/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb @@ -1,20 +1,24 @@ -# Stores articles.pinned, groups.administrative and mail_aliases.smtp_enabled as timestamps, so we -# also know since when they were set (see https://github.com/csvalpha/amber-api/issues/436). +# Stores yes/no flags as timestamps, so we also know since when they were set, e.g. when a user gave +# consent (see https://github.com/csvalpha/amber-api/issues/436). class ReplaceBooleanFlagsWithTimestamps < ActiveRecord::Migration[7.2] FLAGS = [ - %w[articles Article pinned], - %w[groups Group administrative], - %w[mail_aliases MailAlias smtp_enabled] + %w[articles Article pinned pinned_at], + %w[groups Group administrative administrative_at], + %w[mail_aliases MailAlias smtp_enabled smtp_enabled_at], + %w[users User ifes_data_sharing_preference ifes_data_sharing_consented_at], + %w[users User info_in_almanak info_in_almanak_consented_at], + %w[users User allow_sofia_sharing sofia_sharing_consented_at], + %w[users User setup_complete setup_completed_at] ].freeze def up - FLAGS.each do |table, item_type, flag| - add_column table, :"#{flag}_at", :datetime + FLAGS.each do |table, item_type, flag, column| + add_column table, column, :datetime # The flag was set at the last version that turned it on, which paper_trail stored in # object_changes. Records without such a version had it from the start. execute <<~SQL.squish - UPDATE #{table} SET #{flag}_at = COALESCE( + UPDATE #{table} SET #{column} = COALESCE( (SELECT MAX(versions.created_at) FROM versions WHERE versions.item_type = '#{item_type}' AND versions.item_id = #{table}.id AND versions.object_changes -> '#{flag}' ->> 1 = 'true'), @@ -28,10 +32,10 @@ def up end def down - FLAGS.each do |table, _item_type, flag| + FLAGS.each do |table, _item_type, flag, column| add_column table, flag, :boolean, default: false, null: false - execute "UPDATE #{table} SET #{flag} = TRUE WHERE #{flag}_at IS NOT NULL" - remove_column table, :"#{flag}_at" + execute "UPDATE #{table} SET #{flag} = TRUE WHERE #{column} IS NOT NULL" + remove_column table, column end end end diff --git a/db/schema.rb b/db/schema.rb index aab0343b..d28e68d4 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -562,16 +562,16 @@ t.string "picture_publication_preference", default: "always_ask" t.string "emergency_contact" t.string "emergency_number" - t.boolean "ifes_data_sharing_preference", default: false, null: false - t.boolean "info_in_almanak", default: false, null: false t.string "almanak_subscription_preference", default: "physical" t.string "digtus_subscription_preference", default: "physical" t.string "user_details_sharing_preference" - t.boolean "allow_sofia_sharing", default: false, null: false t.string "nickname" t.boolean "trailer_drivers_license", default: false, null: false - t.boolean "setup_complete", default: false, null: false t.string "ical_categories", default: [], array: true + t.datetime "ifes_data_sharing_consented_at" + t.datetime "info_in_almanak_consented_at" + t.datetime "sofia_sharing_consented_at" + t.datetime "setup_completed_at" t.index ["deleted_at"], name: "index_users_on_deleted_at" t.index ["email"], name: "index_users_on_email", unique: true t.index ["login_enabled"], name: "index_users_on_login_enabled" diff --git a/spec/models/concerns/timestamp_flag_spec.rb b/spec/models/concerns/timestamp_flag_spec.rb index 66e6fd07..c2a74b68 100644 --- a/spec/models/concerns/timestamp_flag_spec.rb +++ b/spec/models/concerns/timestamp_flag_spec.rb @@ -26,6 +26,18 @@ it { expect { article.pinned = true }.not_to(change(article, :pinned_at)) } end + context 'when set to false and back to true before saving' do + subject(:article) { create(:article, pinned_at: 1.year.ago) } + + before do + article.pinned = false + article.pinned = true + end + + it { expect(article.pinned_changed?).to be false } + it { expect(article.changed?).to be false } + end + context 'when set to false or nil' do subject(:article) { build(:article, pinned_at: 1.year.ago) } @@ -48,6 +60,14 @@ article.update!(pinned: false) expect(article.saved_change_to_pinned?).to be false end + + context 'when checking from and to' do + before { article.update!(pinned: true) } + + it { expect { article.pinned = false }.to change { article.pinned_changed?(from: true, to: false) }.to(true) } + it { expect { article.pinned = false }.not_to(change { article.pinned_changed?(from: false) }) } + it { expect { article.pinned = true }.not_to(change(article, :pinned_changed?)) } + end end describe 'scopes' do diff --git a/spec/models/import/user_spec.rb b/spec/models/import/user_spec.rb index a6a78960..b7679901 100644 --- a/spec/models/import/user_spec.rb +++ b/spec/models/import/user_spec.rb @@ -10,7 +10,7 @@ subject(:user_import) { described_class.new({ file: test_file, extension: 'csv' }, group) } describe 'when database and required columns are in sync' do - it { expect(User.column_names & required_columns).to match_array(required_columns) } + it { expect(required_columns.select { |c| User.new.respond_to?("#{c}=") }).to match_array(required_columns) } end describe 'when importing users' do diff --git a/spec/requests/v1/groups_controller/index_spec.rb b/spec/requests/v1/groups_controller/index_spec.rb index 4ea21440..cbe8db70 100644 --- a/spec/requests/v1/groups_controller/index_spec.rb +++ b/spec/requests/v1/groups_controller/index_spec.rb @@ -76,6 +76,15 @@ it { expect(json_object_ids.index(administrative_group.id)).to be < json_object_ids.index(other_group.id) } end + context 'when sorting on administrative before name' do + subject(:request) { get("#{record_url}?sort=-administrative,name") } + + let(:administrative_group) { create(:group, name: 'Z', administrative: true) } + let(:other_group) { create(:group, name: 'A', administrative: false) } + + it { expect(json_object_ids.index(administrative_group.id)).to be < json_object_ids.index(other_group.id) } + end + context 'when ascending' do subject(:request) { get("#{record_url}?sort=administrative") } diff --git a/spec/requests/v1/users_controller/update_spec.rb b/spec/requests/v1/users_controller/update_spec.rb index fac85d5c..a62aa284 100644 --- a/spec/requests/v1/users_controller/update_spec.rb +++ b/spec/requests/v1/users_controller/update_spec.rb @@ -32,7 +32,9 @@ digtus_subscription_preference: 'digital', user_details_sharing_preference: 'members_only', phone_number: '+31612345678', - emergency_number: '+31612345678' } + emergency_number: '+31612345678', + info_in_almanak: !record.info_in_almanak, + ifes_data_sharing_preference: !record.ifes_data_sharing_preference } end let(:record_permission) { 'user.update' } end From 51eee8bcf251ef39cfddb096eca9aba0576f074a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:04:23 +0000 Subject: [PATCH 3/3] Store form_responses.completed as completed_at So organisers can see when a response was completed (#436). The API keeps the boolean completed attribute. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SiPSKHKsyFrdS5JjrHUVLg --- app/models/form/response.rb | 4 +++- app/resources/v1/form/response_resource.rb | 2 +- ...0000_replace_boolean_flags_with_timestamps.rb | 3 ++- db/schema.rb | 2 +- spec/models/form/response_spec.rb | 16 ++++++++++++++++ 5 files changed, 23 insertions(+), 4 deletions(-) diff --git a/app/models/form/response.rb b/app/models/form/response.rb index 29140e90..d08153ae 100644 --- a/app/models/form/response.rb +++ b/app/models/form/response.rb @@ -1,5 +1,7 @@ module Form class Response < ApplicationRecord + include TimestampFlag + has_paper_trail belongs_to :form counter_culture :form, column_name: :responses_count @@ -15,7 +17,7 @@ class Response < ApplicationRecord after_create :update_completed_status! before_destroy :destroyable?, unless: :deleted? - scope :completed, -> { where(completed: true) } + timestamp_flag :completed def complete reload unless new_record? # reloading is necessary, to make sure all associations are fresh diff --git a/app/resources/v1/form/response_resource.rb b/app/resources/v1/form/response_resource.rb index 0b932c88..02608491 100644 --- a/app/resources/v1/form/response_resource.rb +++ b/app/resources/v1/form/response_resource.rb @@ -1,6 +1,6 @@ class V1::Form::ResponseResource < V1::ApplicationResource model_name 'Form::Response' - attributes :completed + timestamp_flag_attribute :completed has_one :user, always_include_linkage_data: true has_one :form, always_include_linkage_data: true diff --git a/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb b/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb index bb15dbae..b2372564 100644 --- a/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb +++ b/db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb @@ -8,7 +8,8 @@ class ReplaceBooleanFlagsWithTimestamps < ActiveRecord::Migration[7.2] %w[users User ifes_data_sharing_preference ifes_data_sharing_consented_at], %w[users User info_in_almanak info_in_almanak_consented_at], %w[users User allow_sofia_sharing sofia_sharing_consented_at], - %w[users User setup_complete setup_completed_at] + %w[users User setup_complete setup_completed_at], + %w[form_responses Form::Response completed completed_at] ].freeze def up diff --git a/db/schema.rb b/db/schema.rb index d28e68d4..46f55a78 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -246,8 +246,8 @@ t.datetime "deleted_at", precision: nil t.datetime "created_at", precision: nil, null: false t.datetime "updated_at", precision: nil, null: false - t.boolean "completed", default: false, null: false t.integer "lock_version" + t.datetime "completed_at" t.index ["form_id", "user_id"], name: "index_form_responses_on_form_id_and_user_id_partial", unique: true, where: "(user_id <> 0)" t.index ["user_id"], name: "index_form_responses_on_user_id" end diff --git a/spec/models/form/response_spec.rb b/spec/models/form/response_spec.rb index 0b5b5c0d..24e55a32 100644 --- a/spec/models/form/response_spec.rb +++ b/spec/models/form/response_spec.rb @@ -219,6 +219,22 @@ end end + describe '#completed_at' do + let(:response) { create(:response) } + + before { response.update(completed: false) } + + it 'is set when the response becomes complete' do + response.update(completed: true) + expect(response.completed_at).to be_within(1.minute).of(Time.zone.now) + end + + it 'keeps the original time while the response stays complete' do + response.update(completed: true) + expect { response.update(completed: true) }.not_to(change(response, :completed_at)) + end + end + describe '.completed' do before do create(:response).update(completed: true)