wedding-planner/app/controllers/affinities_controller.rb
Manuel Bustillo 5784c89b79
All checks were successful
Check usage of free licenses / check-licenses (pull_request) Successful in 49s
Add copyright notice / copyright_notice (pull_request) Successful in 1m14s
Run unit tests / unit_tests (pull_request) Successful in 3m25s
Refine endpoint to receive an affinity value and transform it into a discomfort equivalent
2024-12-28 14:19:06 +01:00

37 lines
1.2 KiB
Ruby

# Copyright (C) 2024 Manuel Bustillo
# frozen_string_literal: true
class AffinitiesController < ApplicationController
before_action :set_group
def index
overridden_affinities = @group.affinities
.each_with_object({}) { |affinity, acc| acc[affinity.another_group(@group).id] = affinity.discomfort }
Group.where.not(id: @group.id).pluck(:id).index_with { |group_id| GroupAffinity::MAX_DISCOMFORT - (overridden_affinities[group_id] || GroupAffinity::NEUTRAL) }
.then { |affinities| render json: affinities }
end
def bulk_update
params.expect(affinities: [[:group_id, :affinity]]).map(&:to_h).map do |affinity|
{
group_a_id: @group.id,
group_b_id: affinity[:group_id],
discomfort: GroupAffinity::MAX_DISCOMFORT - affinity[:affinity]
}
end.then { |affinities| GroupAffinity.upsert_all(affinities) }
render json: {}, status: :ok
rescue ActiveRecord::InvalidForeignKey
render json: { error: 'At least one of the group IDs provided does not exist.' }, status: :bad_request
rescue ActiveRecord::StatementInvalid
render json: { error: 'Invalid group ID or discomfort provided.' }, status: :bad_request
end
private
def set_group
@group = Group.find(params[:group_id])
end
end