class UserApi::V2::RecipientsController < UserApi::V2::UserApiBaseController
def create
recipient = UserApi::V2::Recipient.build_tree created_by: current_contact, params: recipient_params
if recipient.save_tree
render json: UserApi::V2::RecipientSerializer.serialize(recipient), status: 200
else
render json: { message: recipient.errors_for_tree.details }, status: 422
end
end
end
class UserApi::V2::Recipient < ::Recipient
def self.build_tree(created_by:, params:)
information = RecipientOrganizationInformation.find_or_initialize_by(
name: params[:name],
legal_form: params[:legal_form]
)
information.tax_id = params[:tax_id]
information.build_organization unless information.organization
new created_by: created_by, information: information
end
def save_tree
transaction do
information.organization.save! unless information.organization.persisted?
information.save! unless information.persisted?
save!
end
rescue StandardError
false
end
end
class V3::RecipientsController < V3::BaseController
def create
recipient_id = SecureRandom.uuid
Fulfillment::Commands::CreateRecipient.call(params.merge id: recipient_id,
created_by: current_user.id
organization_id: current_user.organization_id)
render json: { recipient_id: recipient_id }, status: 200
end
end
class Fulfillment::Commands::CreateRecipient < ::DomainCommand
validations do
required(:id).filled(:str?)
required(:created_by).filled(:str?)
required(:organization_id).filled(:str?)
required(:name).filled(:str?)
# [...]
end
def call(params)
Fulfillment::Events::RecipientCreated.call(params)
end
end
class V3::BaseController < ApplicationController
rescue_from Domain::ParamsError, with: :bad_params
private
def bad_params(e)
render json: { errors: e.message }, status: 422
end
end