2024-12-17 00:46:01 +01:00
|
|
|
# Copyright (C) 2024 Manuel Bustillo
|
|
|
|
|
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class AffinitiesController < ApplicationController
|
2025-01-13 21:16:06 +01:00
|
|
|
before_action :set_group, except: :reset
|
2024-12-17 00:46:01 +01:00
|
|
|
|
|
|
|
def index
|
2024-12-28 18:28:28 +01:00
|
|
|
overridden = @group.affinities.each_with_object({}) do |affinity, acc|
|
|
|
|
acc[affinity.another_group(@group).id] = affinity.discomfort
|
|
|
|
end
|
2025-01-12 20:41:01 +01:00
|
|
|
|
|
|
|
for_each_group do |group_id|
|
|
|
|
overridden[group_id] || GroupAffinity::NEUTRAL
|
|
|
|
end
|
2024-12-17 00:46:01 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def bulk_update
|
2024-12-28 18:28:28 +01:00
|
|
|
affinities = params.expect(affinities: [%i[group_id affinity]]).map(&:to_h).map do |affinity|
|
2024-12-17 00:46:01 +01:00
|
|
|
{
|
|
|
|
group_a_id: @group.id,
|
|
|
|
group_b_id: affinity[:group_id],
|
2024-12-28 14:18:59 +01:00
|
|
|
discomfort: GroupAffinity::MAX_DISCOMFORT - affinity[:affinity]
|
2024-12-17 00:46:01 +01:00
|
|
|
}
|
2024-12-28 18:28:28 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
GroupAffinity.upsert_all(affinities)
|
2024-12-17 00:46:01 +01:00
|
|
|
|
2024-12-28 18:28:28 +01:00
|
|
|
render json: {}, status: :ok
|
2024-12-17 00:46:01 +01:00
|
|
|
rescue ActiveRecord::InvalidForeignKey
|
|
|
|
render json: { error: 'At least one of the group IDs provided does not exist.' }, status: :bad_request
|
|
|
|
rescue ActiveRecord::StatementInvalid
|
2024-12-28 14:18:59 +01:00
|
|
|
render json: { error: 'Invalid group ID or discomfort provided.' }, status: :bad_request
|
2024-12-17 00:46:01 +01:00
|
|
|
end
|
|
|
|
|
2025-01-12 20:41:01 +01:00
|
|
|
def default
|
|
|
|
for_each_group do |group_id|
|
|
|
|
Tables::DiscomfortCalculator.cohesion_discomfort(id_a: @group.id, id_b: group_id).to_f
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2025-01-13 21:16:06 +01:00
|
|
|
def reset
|
|
|
|
affinities = Group.pluck(:id).combination(2).map do |(group_a_id, group_b_id)|
|
|
|
|
{
|
|
|
|
group_a_id:,
|
|
|
|
group_b_id:,
|
|
|
|
discomfort: Tables::DiscomfortCalculator.cohesion_discomfort(id_a: group_a_id, id_b: group_b_id).to_f
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
GroupAffinity.upsert_all(affinities)
|
|
|
|
|
|
|
|
render json: {}, status: :ok
|
|
|
|
end
|
|
|
|
|
2024-12-17 00:46:01 +01:00
|
|
|
private
|
|
|
|
|
2025-01-12 20:41:01 +01:00
|
|
|
def for_each_group
|
|
|
|
Group.where.not(id: @group.id)
|
|
|
|
.pluck(:id)
|
|
|
|
.index_with { |group_id| GroupAffinity::MAX_DISCOMFORT - yield(group_id) }
|
|
|
|
.then { |affinities| render json: affinities }
|
|
|
|
end
|
|
|
|
|
2024-12-17 00:46:01 +01:00
|
|
|
def set_group
|
|
|
|
@group = Group.find(params[:group_id])
|
|
|
|
end
|
|
|
|
end
|