require 'mks/common/methodresponse' module Logistics module Core class OperationService < BaseService def save(params) operation = Operation.new(params) result = operation.save if result OperationSummary.create(:operation => operation) documents = get_additional_documents(params) common_docs = CommonDocument.all converted = convert_documents(operation, documents) common_converted = convert_documents(operation, common_docs) OperationDocument.create(common_converted) OperationDocument.create!(converted) end [result, operation] end # This method takes a list of owner_id / op_ids pairs # and does the assignment # @param: # params -> [{owner_id: 1, op_ids: [2, 3, 4]}, {owner_id: 2, op_ids: [5, 6]}] # def assign_owner(params) op_ids = params.map { |param| param[:op_ids] }.flatten operations = Operation.where(id: op_ids) updated_list = update_owner_data(operations, params) Operation.transaction do updated_list.each(&:save!) end Mks::Common::MethodResponse.new(true, 'Owners Assigned!', nil, nil, nil) rescue ActiveRecord::RecordInvalid => exception Mks::Common::MethodResponse.new(false, nil, nil, [exception.message], nil) end private def get_additional_documents(params) additional_documents = [] param_list = [:transport_mode_id, :declaration_type_id, :client_category_id, :country_of_origin_id, :acquisition_mode_id, :payment_term_id, :delivery_term_id, :container_arrangement_id] params.each do |param| if param_list.include?(param[0].to_sym) str = param[0].to_s.dup clazz_name = str.humanize.split.map(&:capitalize).join clazz = "Logistics::Core::#{clazz_name}".constantize additional_documents += clazz.find(param[1]).additional_documents end end additional_documents end def convert_documents(operation, documents) documents.map do |dt| { :operation => operation, :document => dt.document_type.name, :original => dt.original, :copy => dt.copy, :certified => dt.certified, :is_mandatory => dt.is_mandatory, :is_accepted => false, :source => 'ADDITIONAL' } end end def update_owner_data(operations, params) op_list = [] params.each do |param| op_list += operations.select { |op| param[:op_ids].include?(op.id) } .each { |op| op.owner_id = param[:owner_id] } end op_list end end end end