Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions app/controllers/v1/users_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions app/models/article.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
class Article < ApplicationRecord
include TimestampFlag

mount_base64_uploader :cover_photo, CoverPhotoUploader
has_paper_trail skip: [:cover_photo]

Expand All @@ -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?
Expand Down
56 changes: 56 additions & 0 deletions app/models/concerns/timestamp_flag.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# 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`, `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 # 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_timestamp_flag_change_tracking(name, column)
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] = 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
end
4 changes: 3 additions & 1 deletion app/models/form/response.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module Form
class Response < ApplicationRecord
include TimestampFlag

has_paper_trail
belongs_to :form
counter_culture :form, column_name: :responses_count
Expand All @@ -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
Expand Down
5 changes: 4 additions & 1 deletion app/models/group.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
class Group < ApplicationRecord
include TimestampFlag

mount_base64_uploader :avatar, AvatarUploader
has_paper_trail skip: [:avatar]

Expand All @@ -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]
Expand Down
5 changes: 4 additions & 1 deletion app/models/mail_alias.rb
Original file line number Diff line number Diff line change
@@ -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?
Expand Down
9 changes: 8 additions & 1 deletion app/models/user.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
require 'csv'

class User < ApplicationRecord # rubocop:disable Metrics/ClassLength
include TimestampFlag

has_one_time_password

mount_base64_uploader :avatar, AvatarUploader
Expand Down Expand Up @@ -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|
Expand Down
21 changes: 21 additions & 0 deletions app/resources/v1/application_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,27 @@ 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 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 = {})
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
end

# simplecov:disable
def self.creatable_fields(_context)
[]
Expand Down
3 changes: 2 additions & 1 deletion app/resources/v1/article_resource.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion app/resources/v1/form/response_resource.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down
4 changes: 2 additions & 2 deletions app/resources/v1/group_resource.rb
Original file line number Diff line number Diff line change
@@ -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, filter: true

def avatar_url
@model.avatar.url
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion app/resources/v1/mail_alias_resource.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down
9 changes: 6 additions & 3 deletions app/resources/v1/user_resource.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down
42 changes: 42 additions & 0 deletions db/migrate/20261203120000_replace_boolean_flags_with_timestamps.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# 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 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],
%w[form_responses Form::Response completed completed_at]
].freeze

def up
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 #{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'),
#{table}.created_at
)
WHERE #{table}.#{flag} = TRUE
SQL

remove_column table, flag
end
end

def down
FLAGS.each do |table, _item_type, flag, column|
add_column table, flag, :boolean, default: false, null: false
execute "UPDATE #{table} SET #{flag} = TRUE WHERE #{column} IS NOT NULL"
remove_column table, column
end
end
end
18 changes: 9 additions & 9 deletions db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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"
Expand Down
6 changes: 0 additions & 6 deletions spec/models/article_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading