From 45e3694f2917b0fad696ee4bf9165558674d3ba9 Mon Sep 17 00:00:00 2001 From: Maikanta Gudipudi Date: Fri, 22 Nov 2024 00:34:06 -0600 Subject: [PATCH 1/4] 4 files done --- app/assets/stylesheets/professionPicker.js | 54 ++---- app/controllers/room_controller.rb | 193 ++++++++++----------- app/models/specific_designer.rb | 184 ++++++++++---------- app/models/specific_photographer.rb | 156 +++++++---------- 4 files changed, 259 insertions(+), 328 deletions(-) diff --git a/app/assets/stylesheets/professionPicker.js b/app/assets/stylesheets/professionPicker.js index 95873de76..f1fbfd07a 100644 --- a/app/assets/stylesheets/professionPicker.js +++ b/app/assets/stylesheets/professionPicker.js @@ -1,38 +1,22 @@ $('#general_info_industry').on('change', function(e) { + const options = { + 'Creators': ["Brand Owner", "Designer", "Other Creator"], + 'Services': ["Model", "Photographer", "Sales", "Marketing", "Retail", "Visual", "Content Creator", "Blogger", "Influencer", "Forecasting", "Finances", "Other Services"], + 'Makers': ["Manufacturing", "Materials", "Other Makers"] + }; - const creator_array=["Brand Owner", "Designer", "Other Creator"] - const service_array=["Model", "Photographer", "Sales", "Marketing", "Retail", "Visual", "Content Creator", "Blogger", "Influencer", "Forecasting", "Finances", "Other Services"] - const maker_array=["Manufacturing", "Materials", "Other Makers"] - var values = $(this).val() - console.log("Four friends") - $("#general_info_job_name option").hide() //hide all options - //$('#job_name').selectpicker('deselectAll') //if want to remove all selcted optn - if (values =='Creators') { - $('#general_info_job_name').empty(); - $('#general_info_job_name').append(''); - for (var i = 0; i < 3; i++) { - //$("#profession option[value="' + creator_array[i] + '"]").show() - $('#general_info_job_name').append(''); - } - }else if (values =='Services') { - $('#general_info_job_name').empty(); - $('#general_info_job_name').append(''); - for (var i = 0; i < 12; i++) { - //$("#profession option[value="' + creator_array[i] + '"]").show() - $('#general_info_job_name').append(''); - } - }else if (values =='Makers') { - $('#general_info_job_name').empty(); - $('#general_info_job_name').append(''); - for (var i = 0; i < 3; i++) { - //$("#profession option[value="' + creator_array[i] + '"]").show() - $('#general_info_job_name').append(''); - } + const selectedValue = $(this).val(); + const jobDropdown = $('#general_info_job_name'); + + // Clear and reset the dropdown + jobDropdown.empty(); + if (options[selectedValue]) { + jobDropdown.append(''); // Default option + options[selectedValue].forEach(option => { + jobDropdown.append(``); + }); + } else { + // If no valid selection, show a default option or hide all + jobDropdown.append(''); } - else { - // dont show anything - $("#general_info_job_name option").hide() - //$("#general_info_job_name option").show() //show all options - } - //$('#job_name').selectpicker('refresh'); //refresh selctpicker -}); \ No newline at end of file +}); diff --git a/app/controllers/room_controller.rb b/app/controllers/room_controller.rb index 1e57e2324..8ada30b4a 100644 --- a/app/controllers/room_controller.rb +++ b/app/controllers/room_controller.rb @@ -1,121 +1,102 @@ class RoomController < ApplicationController def show - if session[:current_user_key] != nil or params[:user_key] != nil - - user_key_current = params[:user_key] || session[:current_user_key] - @error = user_key_current.to_s - puts "sessions current_user_key" + user_key_current.to_s - - @user = GeneralInfo.find_by(userKey: user_key_current) - user_ids = Message.where("general_info_id = ? OR chatting_with = ?", @user[:id], @user[:id]) - .pluck(:general_info_id, :chatting_with) - .flatten - .uniq - - @users = user_ids.present? ? GeneralInfo.where(id: user_ids).where.not(userKey: user_key_current).order(updated_at: :desc) : nil - @allusers = GeneralInfo.where.not(userKey: user_key_current) - @loader = true - - if @user && @user.notification - @notifications_from = @user.notification_from - end - - if params[:id] - @chatting_with = GeneralInfo.find_by(id: params[:id]) - @chatname = @chatting_with[:first_name] - @chatid = params[:id] - @chatlink = "/dm/" + @chatid - - @room = Room.new - @room_name = get_name(@user, @chatting_with) - @single_room = Room.where(name: @room_name).first || Room.create_private_room([@user, @chatting_with], @room_name) - @room_id = @single_room[:id] - - @messages = Message.where(room_id: @room_id).order(created_at: :asc) - @loader = false - - if @user.notification - @new_notification_from = [] - - @notifications_from.each do |n| - if n != @chatid.to_i - @new_notification_from.append(n) - end - end - - if @new_notification_from.length() == 0 - @user.notification = false - end - - @notifications_from = @new_notification_from - @user.notification_from = @new_notification_from - - @user.save - end - end - - if GeneralInfo.exists?(:userKey => user_key_current) - @gallery = Gallery.all - @general_info = GeneralInfo.find_by(userKey: user_key_current) - @general_info_attributes = GeneralInfo.attribute_names - @general_info_values = @general_info.attribute_values - @login_info = LoginInfo.find_by(userKey: user_key_current) - if LoginInfo.find_by(userKey: @general_info.userKey) - @email = LoginInfo.find_by(userKey: @general_info.userKey).email - end - #@adminMaker = GeneralInfo.make_admin(params[:room]) - using_default = false - - if session[:current_user_key] != nil and params[:user_key] == nil - @login_user_true = session[:current_user_key] - end - - @username = @general_info[:first_name] - end - else - redirect_to "/login_info/login" + user_key_current = params[:user_key] || session[:current_user_key] + return redirect_to "/login_info/login" if user_key_current.nil? + + @user = GeneralInfo.find_by(userKey: user_key_current) + return redirect_to "/login_info/login" unless @user + + fetch_users_and_notifications(user_key_current) + + if params[:id] + setup_chat(params[:id]) + handle_notifications end + + fetch_general_info(user_key_current) end def create_message - if session[:current_user_key] != nil or params[:user_key] != nil - - user_key_current = params[:user_key] || session[:current_user_key] - @error = user_key_current.to_s - puts "sessions current_user_key" + user_key_current.to_s - - @user = GeneralInfo.find_by(userKey: user_key_current) - - if params[:id] - @chatting_with = GeneralInfo.find_by(id: params[:id]) - @chatname = @chatting_with[:first_name] - @chatid = params[:id] - @chatlink = "/dm/" + @chatid - - @room = Room.new - @room_name = get_name(@user, @chatting_with) - @single_room = Room.where(name: @room_name).first || Room.create_private_room([@user, @chatting_with], @room_name) - - @message = Message.create(general_info_id: @user[:id], room_id: @single_room[:id], body: params[:body], chatting_with: @chatid) - # Check if there are any files in params[:files] and attach them - if params[:files].present? - @message.files.attach(params[:files]) - end - end - - redirect_to @chatlink - else - redirect_to "/login_info/login" + user_key_current = params[:user_key] || session[:current_user_key] + return redirect_to "/login_info/login" if user_key_current.nil? + + @user = GeneralInfo.find_by(userKey: user_key_current) + return redirect_to "/login_info/login" unless @user + + create_new_message(params[:id], params[:body], params[:files]) if params[:id] + end + + private + + def fetch_users_and_notifications(user_key_current) + user_ids = Message.where("general_info_id = ? OR chatting_with = ?", @user[:id], @user[:id]) + .pluck(:general_info_id, :chatting_with) + .flatten.uniq + + @users = user_ids.present? ? GeneralInfo.where(id: user_ids).where.not(userKey: user_key_current).order(updated_at: :desc) : nil + @allusers = GeneralInfo.where.not(userKey: user_key_current) + @loader = true + + @notifications_from = @user.notification_from if @user&.notification + end + + def setup_chat(chat_id) + @chatting_with = GeneralInfo.find_by(id: chat_id) + return unless @chatting_with + + @chatname = @chatting_with[:first_name] + @chatid = chat_id + @chatlink = "/dm/#{@chatid}" + + @room_name = get_name(@user, @chatting_with) + @single_room = Room.find_or_create_by(name: @room_name) do |room| + Room.create_private_room([@user, @chatting_with], @room_name) end + @room_id = @single_room[:id] + + @messages = Message.where(room_id: @room_id).order(:created_at) + @loader = false end - #def show_notifications - - #end + def handle_notifications + return unless @user.notification + + @new_notification_from = @notifications_from.reject { |n| n == @chatid.to_i } + @user.update(notification: @new_notification_from.any?, notification_from: @new_notification_from) + end + + def fetch_general_info(user_key_current) + return unless GeneralInfo.exists?(userKey: user_key_current) + + @gallery = Gallery.all + @general_info = GeneralInfo.find_by(userKey: user_key_current) + return unless @general_info + + @general_info_attributes = @general_info.attribute_names + @general_info_values = @general_info.attribute_values + @login_info = LoginInfo.find_by(userKey: user_key_current) + @username = @general_info[:first_name] + end + + def create_new_message(chat_id, body, files) + @chatting_with = GeneralInfo.find_by(id: chat_id) + return unless @chatting_with + + @chatlink = "/dm/#{chat_id}" + @room_name = get_name(@user, @chatting_with) + @single_room = Room.find_or_create_by(name: @room_name) do |room| + Room.create_private_room([@user, @chatting_with], @room_name) + end + + @message = Message.create(general_info_id: @user[:id], room_id: @single_room[:id], body: body, chatting_with: chat_id) + @message.files.attach(files) if files.present? + + redirect_to @chatlink + end - private def get_name(user1, user2) user = [user1.id, user2.id].sort "private_#{user[0]}_#{user[1]}" end end + diff --git a/app/models/specific_designer.rb b/app/models/specific_designer.rb index 67e82dc1c..b4026aafd 100644 --- a/app/models/specific_designer.rb +++ b/app/models/specific_designer.rb @@ -1,105 +1,97 @@ - class SpecificDesigner < ApplicationRecord - attr_accessor :allgenres +class SpecificDesigner < ApplicationRecord + attr_accessor :allgenres - def self.search checkboxes, general_info_user_keys, experience_arg - @user_array = Array.new - @genre_checked_array = Array.new - @return_array = Array.new + def self.search(checkboxes, general_info_user_keys, experience_arg) + @user_array = fetch_user_array(general_info_user_keys) + @genre_checked_array = fetch_genre_checked_array(@user_array, checkboxes) + @return_array = fetch_return_array(@genre_checked_array, experience_arg) + @return_array + end - # Search based on the room keys retrieved from GeneralInfo, store into @user_array - if (general_info_user_keys.length > 0) - # Gets here if general_info_user_keys has entries - general_info_user_keys.each do |user_key_element| - if SpecificDesigner.exists?(user_key: user_key_element) - @user_array.push(SpecificDesigner.find_by(user_key: user_key_element)) - end - end - else - # Gets here if nothing came through general_info_user_keys - end + # Sets appearance of profile view attributes + def attribute_values + # Define attributes to be processed + attributes = { + influencers: "Influencers: ", + specialties: "Specialities: ", + compensation: "Compensation: ", + experience: "Experience: " + } + + # Initialize the attribute values hash + @attribute_values = {} - # Genre requires a slightly different search - # For every room in user_array, check if A genre matches ANY genre - # If there are no genres, loop through @user_array & push the keys into @genre_checked_array - if checkboxes.nil? - # Gets here if genre is empty - # Leave genre checked hash empty since we're not searching for genres - elsif !(@user_array.length > 0) - # They did not search for anything in GeneralInfo and room array never got populated, - # Therefore they are looking for everyone in the profession, using genres - SpecificDesigner.all.find_each do |user_object| - checkboxes.each do |key, checkbox_genre| - if user_object[:genre].to_s.include? key.to_s - @genre_checked_array.push(user_object) - break - end - end - end - else - # Gets here if user_array has entries - @user_array.each do |user_object| - checkboxes.each do |key, checkbox_genre| - if user_object[:genre].to_s.include? key.to_s - @genre_checked_array.push(user_object) - break - end - end - end - end + # Loop through each attribute and assign its value + attributes.each do |key, label| + @attribute_values[key] = "#{label}#{self[key].to_s}" + end + + # Handle genre attribute separately + @attribute_values[:genre] = "Genre(s): " + if self.genre.present? + @attribute_values[:genre] += self.genre.split(",").map(&:strip).join(", ") + end - # 1st check that there are any params worth searching - if !experience_arg.nil? - if(@genre_checked_array.length > 0) - # Can search by experience & previous genre-checked results - @genre_checked_array.each do |user_object| - if SpecificDesigner.where("user_key ILIKE ? AND experience ILIKE ?)" , user_object[:user_key], @experiece_arg) - @return_array.push(user_object[:user_key]) - end - end - else - # Can search by experience but have no previous genre-checked results - # Search entire model and check for the params - SpecificDesigner.all.find_each do |user_object| - if SpecificDesigner.where("user_key ILIKE ?", user_object[:user_key]) - @return_array.push(user_object[:user_key]) #Might need to find by instead... very worse in efficiency tbh. - end - end - end - else - if(@genre_checked_array.length > 0) - # Have no experience to search by but have genre-checks - # Return genre-checked results - @genre_checked_array.each do |user_object| - @return_array.push(user_object[:user_key]) - end - else - # Have no experience to search by and no genre-checked results - # Return everything in the table - SpecificDesigner.all.find_each do |user_object| - @return_array.push(user_object[:user_key]) - end - end - end + @attribute_values + end - return @return_array - end + private - # Sets appearance of profile view attributes - def attribute_values - @attribute_values = Hash.new - @attribute_values[:influencers] = "Influencers: " + self.influencers.to_s - @attribute_values[:specialties] = "Specialities: " + self.specialties.to_s - @attribute_values[:compensation] = "Compensation: " + self.compensation.to_s - @attribute_values[:experience] = "Experience: " + self.experience.to_s + def self.fetch_user_array(general_info_user_keys) + user_array = [] + general_info_user_keys.each do |user_key_element| + user = SpecificDesigner.find_by(user_key: user_key_element) + user_array.push(user) if user + end + user_array + end - @attribute_values[:genre] = "Genre(s): " - if self.genre != nil - self.genre.split(",").each do |genre| - @attribute_values[:genre] += genre + ", " - end - @attribute_values[:genre] = @attribute_values[:genre][0, @attribute_values[:genre].length-2] - end + def self.fetch_genre_checked_array(user_array, checkboxes) + genre_checked_array = [] - @attribute_values - end + if checkboxes.nil? + # No genres to search, leave genre_checked_array empty + elsif user_array.empty? + SpecificDesigner.all.find_each do |user_object| + if checkboxes.keys.any? { |key| user_object[:genre].to_s.include?(key.to_s) } + genre_checked_array.push(user_object) + end + end + else + user_array.each do |user_object| + if checkboxes.keys.any? { |key| user_object[:genre].to_s.include?(key.to_s) } + genre_checked_array.push(user_object) + end + end + end + + genre_checked_array + end + + def self.fetch_return_array(genre_checked_array, experience_arg) + return_array = [] + + if experience_arg.present? + if genre_checked_array.any? + genre_checked_array.each do |user_object| + if SpecificDesigner.where("user_key ILIKE ? AND experience ILIKE ?", user_object[:user_key], experience_arg).exists? + return_array.push(user_object[:user_key]) + end + end + else + SpecificDesigner.all.find_each do |user_object| + if SpecificDesigner.where("user_key ILIKE ?", user_object[:user_key]).exists? + return_array.push(user_object[:user_key]) + end + end + end + elsif genre_checked_array.any? + genre_checked_array.each { |user_object| return_array.push(user_object[:user_key]) } + else + SpecificDesigner.all.find_each { |user_object| return_array.push(user_object[:user_key]) } + end + + return_array + end end + diff --git a/app/models/specific_photographer.rb b/app/models/specific_photographer.rb index ea1250c8f..e2e4ef002 100644 --- a/app/models/specific_photographer.rb +++ b/app/models/specific_photographer.rb @@ -1,91 +1,65 @@ - class SpecificPhotographer < ApplicationRecord - attr_accessor :allgenres - - def self.search params_arg - @final_return = [] - - if params_arg.length > 0 - GeneralInfo.all.find_each do |user_object| - - if user_object[:specific_profile_id] == 3 - spec_object = SpecificPhotographer.find_by(user_key: user_object["userKey"]) - - puts spec_object.inspect - - incl = true - params_arg.each do |param_key, param_val| - if param_key == "checkboxes" - next - end - - chk_val = user_object[param_key] - - if chk_val == nil - puts param_key - chk_val = spec_object[param_key] - end - - if chk_val != param_val - incl = false - end - end - - # GENRE CHECKING - - if spec_object - if params_arg["checkboxes"] && incl && spec_object["genre"] - genre_arr = spec_object["genre"].split(",") - - puts genre_arr - - genre_incl = false - params_arg["checkboxes"].each do |genre| - if genre_arr.include? genre - puts genre - genre_incl = true - end - end - - incl = genre_incl - else - incl = false - end - - if incl - @final_return.push(user_object[:userKey]) - end - else - incl = false - end - end - end - else - GeneralInfo.all.find_each do |user_object| - if user_object[:specific_profile_id] == 3 - @final_return.push(user_object[:userKey]) - end - end - end - - return @final_return - end - - # Sets appearance of profile view attributes - def attribute_values - @attribute_values = Hash.new - @attribute_values[:influencers] = "Influencers: " + self.influencers.to_s - @attribute_values[:specialties] = "Specialities: " + self.specialties.to_s - @attribute_values[:compensation] = "Compensation: " + self.compensation.to_s - @attribute_values[:experience] = "Experience: " + self.experience.to_s - - @attribute_values[:genre] = "Genre(s): " - if self.genre != nil - self.genre.split(",").each do |genre| - @attribute_values[:genre] += genre + ", " - end - @attribute_values[:genre] = @attribute_values[:genre][0, @attribute_values[:genre].length-2] - end - - @attribute_values - end - end +class SpecificPhotographer < ApplicationRecord + attr_accessor :allgenres + + def self.search(params_arg) + @final_return = [] + + if params_arg.empty? + # Handle the no-parameters case explicitly + GeneralInfo.where(specific_profile_id: 3).find_each do |user_object| + @final_return.push(user_object[:userKey]) + end + return @final_return + end + + GeneralInfo.where(specific_profile_id: 3).find_each do |user_object| + spec_object = SpecificPhotographer.find_by(user_key: user_object["userKey"]) + next unless spec_object + + if params_match?(params_arg, user_object, spec_object) && + genre_match?(params_arg["checkboxes"], spec_object["genre"]) + @final_return.push(user_object[:userKey]) + end + end + + @final_return + end + + # Checks if user attributes and params match + def self.params_match?(params_arg, user_object, spec_object) + params_arg.all? do |param_key, param_val| + next true if param_key == "checkboxes" + + chk_val = user_object[param_key] || spec_object[param_key] + chk_val == param_val + end + end + + # Checks if genres match + def self.genre_match?(checkboxes, genre_string) + return true unless checkboxes + return false unless genre_string + + genre_arr = genre_string.split(",") + checkboxes.any? { |genre| genre_arr.include?(genre) } + end + + def attribute_values + { + influencers: "Influencers: #{influencers}", + specialties: "Specialities: #{specialties}", + compensation: "Compensation: #{compensation}", + experience: "Experience: #{experience}", + genre: format_genres + } + end + + private + + def format_genres + return "Genre(s): " unless genre + + genre_list = genre.split(",").map(&:strip).join(", ") + "Genre(s): #{genre_list}" + end +end \ No newline at end of file From 8143d4a8b9fc4feac5f9bd8b9018616315e9bb83 Mon Sep 17 00:00:00 2001 From: Maikanta Gudipudi Date: Fri, 22 Nov 2024 03:15:37 -0600 Subject: [PATCH 2/4] code climate admin,profile,general_info,specific_midel --- app/controllers/admin/admin_controller.rb | 228 +++++----- app/controllers/show_profile_controller.rb | 189 ++++---- app/models/general_info.rb | 489 ++++++++++----------- app/models/specific_model.rb | 266 +++++------ 4 files changed, 533 insertions(+), 639 deletions(-) diff --git a/app/controllers/admin/admin_controller.rb b/app/controllers/admin/admin_controller.rb index 5bef062cf..c27f5069b 100644 --- a/app/controllers/admin/admin_controller.rb +++ b/app/controllers/admin/admin_controller.rb @@ -5,147 +5,139 @@ class AdminController < ApplicationController def landing - #GeneralInfo.load_Job_File #No longer needed- Job file is loaded in initializer - @hasPermission = false - print('Current USer Key is: ') - print(session[:current_user_key]) - if (session[:current_user_key] != nil && GeneralInfo.exists?(:userKey => session[:current_user_key])) - general_info = GeneralInfo.find_by(userKey: session[:current_user_key]) - @hasPermission = general_info.is_admin - end - if(@hasPermission == false) - redirect_to "/login_info/login" - end - + @hasPermission = check_admin_permission + redirect_to "/login_info/login" unless @hasPermission end def create - - @hasPermission = false - if (session[:current_user_key] != nil && GeneralInfo.exists?(:userKey => session[:current_user_key])) - general_info = GeneralInfo.find_by(userKey: session[:current_user_key]) - @hasPermission = general_info.is_admin - end - # if(@hasPermission == false) - # redirect_to "/login_info/login" - # end - + @hasPermission = check_admin_permission @potentialJob = params[:job_name].to_s - - - if(@potentialJob != nil && @potentialJob != "") + + if @potentialJob.present? @potentialJob = @potentialJob.parameterize(separator: '_').upcase_first - if(GeneralInfo.check_Job?(@potentialJob) == false) - GeneralInfo.create_Job(@potentialJob) - init = @potentialJob.constantize.new - flash.now[:notice] = @potentialJob.titleize + " has been created.\nCurrent jobs are : " + GeneralInfo.see_Jobs.join(",") - else - flash.now[:notice] = params[:job_name].titleize + " already exists.\nCurrent jobs are : " + GeneralInfo.see_Jobs.join(",") - end - elsif(params[:job_name] == "") + if GeneralInfo.check_Job?(@potentialJob) == false + GeneralInfo.create_Job(@potentialJob) + flash.now[:notice] = "#{@potentialJob.titleize} has been created.\nCurrent jobs are : #{GeneralInfo.see_Jobs.join(",")}" + else + flash.now[:notice] = "#{params[:job_name].titleize} already exists.\nCurrent jobs are : #{GeneralInfo.see_Jobs.join(",")}" + end + elsif @potentialJob.blank? flash.now[:notice] = "Please enter a non-empty value." end - - # else - # Probably fetching page - - end def edit - - @hasPermission = false - if (session[:current_user_key] != nil && GeneralInfo.exists?(:userKey => session[:current_user_key])) - general_info = GeneralInfo.find_by(userKey: session[:current_user_key]) - @hasPermission = general_info.is_admin - end - if(@hasPermission == false) - redirect_to "/login_info/login" - end - - @jobs = Array.new - - GeneralInfo.see_Jobs.each do |i| - @jobs.push i.titleize - end - - if(params[:job_name] != nil && params[:attr_action] != nil && params[:attr_name] != nil) - @job = params[:job_name].parameterize(separator: '_').upcase_first - @job_Obj = params[:job_name].parameterize(separator: '_').upcase_first.constantize - @action = params[:attr_action] - @attr = params[:attr_name] - - if(GeneralInfo.check_Job?(@job)) - if(@action == 'Add' && @job_Obj.view_Attr().include?(@attr) == false) - @job_Obj.add_Attr(@attr) - flash.now[:notice] = "Attribute " + @attr + " added to " + @job.to_s + "---" + @job + "\'s current attributes are " + @job_Obj.view_Attr.inspect - x = @job_Obj.view_Attr().find_index(@attr) - GeneralInfo.find_each do |user| - if(user[:job_name] == @job_Obj.name) - newAttr = user[:job_attr] - newAttr[x] = "Default" - user.update_attribute(:job_attr, newAttr) - end - end - elsif(@action == 'Remove' && @job_Obj.view_Attr().include?(@attr)) - origLoc = @job_Obj.view_Attr().find_index(@attr) - @job_Obj.delete_Attr(@attr) - flash.now[:notice] = "Attribute " + @attr + " removed from " + @job + "---" + @job + "\'s current attributes are " + @job_Obj.view_Attr.inspect - attrLength = @job_Obj.view_Attr().length - GeneralInfo.find_each do |user| - if(user[:job_name] == @job_Obj.name) - x = origLoc - newAttr = user[:job_attr] - while (x < attrLength) - newAttr[x] = newAttr[x + 1] - x += 1 - end - newAttr.delete(attrLength) - user.update_attribute(:job_attr, newAttr) - end - end - else - flash.now[:notice] = "Attribute " + @attr + " already in " + @job.to_s + "---" + @job + "\'s current attributes are " + @job_Obj.view_Attr.inspect - end - - else - flash.now[:notice] = "Job " + @job.titleize + " not found." - end + @hasPermission = check_admin_permission + redirect_to "/login_info/login" unless @hasPermission + + @jobs = GeneralInfo.see_Jobs.map(&:titleize) + + if params[:job_name].present? && params[:attr_action].present? && params[:attr_name].present? + @job = params[:job_name].parameterize(separator: '_').upcase_first + @job_Obj = @job.constantize + @action = params[:attr_action] + @attr = params[:attr_name] + + if GeneralInfo.check_Job?(@job) + handle_attribute_action else - flash.now[:notice] = "Error: One or more empty fields" + flash.now[:notice] = "Job #{@job.titleize} not found." end + else + flash.now[:notice] = "Error: One or more empty fields" + end end def delete + @hasPermission = check_admin_permission + redirect_to "/login_info/login" unless @hasPermission + + @jobs = GeneralInfo.see_Jobs.map(&:titleize) + + if params[:job_name].present? + @potentialJob = params[:job_name].to_s.parameterize(separator: '_').upcase_first + if GeneralInfo.check_Job?(@potentialJob) + GeneralInfo.delete_Job(@potentialJob) + flash.now[:notice] = "#{params[:job_name].titleize} has been deleted." + end + end + end - @hasPermission = false - if (session[:current_user_key] != nil && GeneralInfo.exists?(:userKey => session[:current_user_key])) - general_info = GeneralInfo.find_by(userKey: session[:current_user_key]) - @hasPermission = general_info.is_admin + private + # Extracted method to check admin permission + def check_admin_permission + if session[:current_user_key].present? && GeneralInfo.exists?(userKey: session[:current_user_key]) + general_info = GeneralInfo.find_by(userKey: session[:current_user_key]) + general_info.is_admin + else + false end - if(@hasPermission == false) - redirect_to "/login_info/login" + end + + # Extracted method to handle the Add/Remove actions for attributes + def handle_attribute_action + if @action == 'Add' + add_attribute + elsif @action == 'Remove' + remove_attribute + else + flash.now[:notice] = "Attribute #{@attr} already in #{@job.titleize}---#{@job}'s current attributes are #{@job_Obj.view_Attr.inspect}" end + end - @jobs = Array.new - - - if(params[:job_name] != nil) - @potentialJob = params[:job_name].to_s.parameterize(separator: '_').upcase_first - if(GeneralInfo.check_Job?(@potentialJob)) - GeneralInfo.delete_Job(@potentialJob) - flash.now[:notice] = params[:job_name].titleize + " has been deleted." + # Add attribute to job + def add_attribute + if @job_Obj.view_Attr.include?(@attr) + flash.now[:notice] = "Attribute #{@attr} already in #{@job.titleize}---#{@job.titleize}'s current attributes are #{@job_Obj.view_Attr.inspect}" + else + @job_Obj.add_Attr(@attr) + update_users_job_attributes + flash.now[:notice] = "Attribute #{@attr} added to #{@job.titleize}---#{@job.titleize}'s current attributes are #{@job_Obj.view_Attr.inspect}" + end + end + + # Remove attribute from job + def remove_attribute + if @job_Obj.view_Attr.include?(@attr) + original_location = @job_Obj.view_Attr.find_index(@attr) + @job_Obj.delete_Attr(@attr) + update_users_job_attributes_after_removal(original_location) + flash.now[:notice] = "Attribute #{@attr} removed from #{@job.titleize}---#{@job.titleize}'s current attributes are #{@job_Obj.view_Attr.inspect}" + else + flash.now[:notice] = "Attribute #{@attr} not found in #{@job.titleize}." + end + end - #GeneralInfo.delete_Job_From_File(params[:job_name]) - end - #else - # Probably fetching page + # Extracted method to update job attributes for all users + def update_users_job_attributes + GeneralInfo.find_each do |user| + if user[:job_name] == @job_Obj.name + Rails.logger.debug("user.job_attr is #{user.job_attr.class}") # Log the class of job_attr + if user.job_attr.is_a?(Array) + user.job_attr += [@attr] + elsif user.job_attr.is_a?(Hash) + user.job_attr[@attr] = "Default" # Or appropriate logic for a hash + else + Rails.logger.error("Unexpected type for job_attr") + end + user.save + end end + end - GeneralInfo.see_Jobs.each do |i| - @jobs.push i.titleize + # Extracted method to update job attributes for users after removing an attribute + def update_users_job_attributes_after_removal(original_location) + GeneralInfo.find_each do |user| + if user[:job_name] == @job_Obj.name + new_attributes = user[:job_attr] + if new_attributes.is_a?(Array) + new_attributes.delete_at(original_location) + user.update_attribute(:job_attr, new_attributes) + else + Rails.logger.error("Expected Array for job_attr, but got #{new_attributes.class}") + end + end end - end end end diff --git a/app/controllers/show_profile_controller.rb b/app/controllers/show_profile_controller.rb index d093c9e83..8b09f014e 100644 --- a/app/controllers/show_profile_controller.rb +++ b/app/controllers/show_profile_controller.rb @@ -2,119 +2,31 @@ class ShowProfileController < ApplicationController # Associated with the view that displays after a profile is selected from the search results list def show_profile @gallery_taggings = GalleryTagging.all - logger.info("Debuggging Star rating:") + logger.info("Debugging Star rating:") logger.debug(@gallery.inspect) + if session[:current_user_key] != nil or params[:user_key] != nil user_key_current = params[:user_key] || session[:current_user_key] @error = user_key_current.to_s puts "sessions current_user_key" + user_key_current.to_s - + @user = GeneralInfo.find_by(userKey: user_key_current) - - if @user && @user.notification - @notifications_from = @user.notification_from - end - + load_notifications if @user && @user.notification + if GeneralInfo.exists?(:userKey => user_key_current) - @gallery = Gallery.all - @general_info = GeneralInfo.find_by(userKey: user_key_current) - @general_info_attributes = GeneralInfo.attribute_names - @general_info_values = @general_info.attribute_values - @login_info = LoginInfo.find_by(userKey: user_key_current) - if LoginInfo.find_by(userKey: @general_info.userKey) - @email = LoginInfo.find_by(userKey: @general_info.userKey).email - end - #@adminMaker = GeneralInfo.make_admin(params[:room]) - using_default = false - - if session[:current_user_key] != nil and params[:user_key] == nil - @login_user_true = session[:current_user_key] - end - - @username = @general_info[:first_name] - - @on_Own = false - if session[:current_user_key] == user_key_current - @on_Own = true - end - - @is_Admin = false - if GeneralInfo.find_by(userKey: session[:current_user_key]) != nil - @is_Admin = GeneralInfo.find_by(userKey: session[:current_user_key]).is_admin - @addUser = user_key_current - end - puts @addUser.inspect - @job_title = @general_info[:job_name] - if (@job_title == "" || @job_title == nil) - @job_title = "Photographer" - using_default = true - end - - if (GeneralInfo.check_Job?(@job_title)&& !using_default) - #@attr_titles = @job_title.constantize.view_Attr() - #@attr_types = @job_title.constantize.view_Attr_Type() - #@attr_contents = @general_info[:job_attr] - - #@profile_type = @job_title #@general_info_values[:job_name] - @attribute_titles = @job_title.constantize.view_Attr() - @attribute_types = @job_title.constantize.view_Attr_Type() - @attribute_contents = @general_info_values[:job_attr] - else - @attribute_titles = Hash.new - @attribute_types = Array.new - @attribute_contents = Hash.new - end - puts @general_info.inspect - # Start of messy profile selection - case @general_info.specific_profile_id - when 1 - # @profile_type = "Designer" - # if SpecificDesigner.exists?(:user_key => user_key_current) - # @specific_designer = SpecificDesigner.find_by(user_key: user_key_current) - # @profile_info = @specific_designer.attribute_values - # else - # @profile_info = nil - # end - when 2 - # @profile_type = "Model" - # if SpecificModel.exists?(:user_key => user_key_current) - # @specific_model = SpecificModel.find_by(user_key: user_key_current) - # @profile_info = @specific_model.attribute_values - # else - # @profile_info = nil - # end - when 3 - # @profile_type = "Photographer" - # if SpecificPhotographer.exists?(:user_key => user_key_current) - # @specific_photographer = SpecificPhotographer.find_by(user_key: user_key_current) - # @profile_info = @specific_photographer.attribute_values - # else - # @profile_info = nil - # end - else - puts "Unknown profile type! Profile type given: " - @profile_type = "Error" - end - @followers = @user.get_followers - @following = @user.get_users_they_follow - current_user = GeneralInfo.find_by(userKey: session[:current_user_key]) - @currently_following = Follow.exists?(:follower => current_user, :followee => @user) - # End of Messy Profile Selection - puts @profile_info.inspect + load_general_info(user_key_current) + set_profile_data(user_key_current) + check_admin_and_own_profile(user_key_current) + load_job_info(user_key_current) + handle_profile_selection(user_key_current) + load_following_data(user_key_current) else - #SHOULD SHOW BLANK STUFF!!!! - # @job_title = "No Profile Selected" - # @general_info = GeneralInfo.new - # @general_info_values = Hash.new - # @attribute_titles = Hash.new - # @attribute_types = Array.new - # @attribute_contents = Hash.new + # SHould show blank stuff end else redirect_to "/login_info/login" end puts @attribute_titles.inspect - end def destroy @@ -126,8 +38,75 @@ def destroy @gallery.destroy redirect_to '/show_profile' end - - - - -end + + private + + # Extracted method for loading notifications + def load_notifications + @notifications_from = @user.notification_from + end + + # Extracted method for loading general info + def load_general_info(user_key_current) + @gallery = Gallery.all + @general_info = GeneralInfo.find_by(userKey: user_key_current) + @general_info_attributes = GeneralInfo.attribute_names + @general_info_values = @general_info.attribute_values + @login_info = LoginInfo.find_by(userKey: user_key_current) + @email = @login_info&.email + end + + # Extracted method for setting profile data + def set_profile_data(user_key_current) + @username = @general_info[:first_name] + @on_Own = session[:current_user_key] == user_key_current + @is_Admin = GeneralInfo.find_by(userKey: session[:current_user_key])&.is_admin || false + @job_title = @general_info[:job_name].presence || "Photographer" + end + + # Extracted method for loading job info + def load_job_info(user_key_current) + using_default = @job_title == "Photographer" + if GeneralInfo.check_Job?(@job_title) && !using_default + @attribute_titles = @job_title.constantize.view_Attr + @attribute_types = @job_title.constantize.view_Attr_Type + @attribute_contents = @general_info_values[:job_attr] + else + @attribute_titles = {} + @attribute_types = [] + @attribute_contents = {} + end + end + + # Extracted method for handling profile selection + def handle_profile_selection(user_key_current) + case @general_info.specific_profile_id + when 1 + # Load SpecificDesigner if exists + # @specific_designer = SpecificDesigner.find_by(user_key: user_key_current) + when 2 + # Load SpecificModel if exists + # @specific_model = SpecificModel.find_by(user_key: user_key_current) + when 3 + # Load SpecificPhotographer if exists + # @specific_photographer = SpecificPhotographer.find_by(user_key: user_key_current) + else + @profile_type = "Error" + end + end + + # Extracted method for loading following data + def load_following_data(user_key_current) + @followers = @user.get_followers + @following = @user.get_users_they_follow + current_user = GeneralInfo.find_by(userKey: session[:current_user_key]) + @currently_following = Follow.exists?(follower: current_user, followee: @user) + end + + # Extracted method for checking admin and own profile + def check_admin_and_own_profile(user_key_current) + if GeneralInfo.find_by(userKey: session[:current_user_key]) + @addUser = user_key_current + end + end +end \ No newline at end of file diff --git a/app/models/general_info.rb b/app/models/general_info.rb index a094b8554..d59653479 100644 --- a/app/models/general_info.rb +++ b/app/models/general_info.rb @@ -50,64 +50,38 @@ def address # self[:name] # end - def self.search searchArg - location = nil - if searchArg[:location].present? and searchArg[:location] != '' - location = searchArg[:location] - end - - distance = 20 - if searchArg[:distance].present? and searchArg[:distance] != '' - distance = Integer(searchArg[:distance]) - end - - if location != nil - query = GeneralInfo.near(location, distance) - else - query = GeneralInfo.all - end - - if searchArg[:first_name].present? - if searchArg[:first_name_regex] == 'Contains' - searchArg[:first_name] = "%" + searchArg[:first_name] + "%" - elsif searchArg[:first_name_regex] == 'Starts With' - searchArg[:first_name] = searchArg[:first_name] + "%" - elsif searchArg[:first_name_regex] == 'Ends With' - searchArg[:first_name] = "%" + searchArg[:first_name] - elsif searchArg[:first_name_regex] == 'Exactly Matches' - searchArg[:first_name] = searchArg[:first_name] - end - query = query.where("first_name ILIKE ?", searchArg[:first_name]) - end - - if searchArg[:last_name].present? - if searchArg[:last_name_regex]=='Contains' - searchArg[:last_name]="%"+searchArg[:last_name]+"%" - elsif searchArg[:last_name_regex]=='Starts With' - searchArg[:last_name]=searchArg[:last_name]+"%" - elsif searchArg[:last_name_regex]=='Ends With' - searchArg[:last_name]="%"+searchArg[:last_name] - elsif searchArg[:last_name_regex]=='Exactly Matches' - searchArg[:last_name]=searchArg[:last_name] - end - query = query.where("last_name ILIKE ?", searchArg[:last_name]) - end - - if searchArg[:gender].present? and searchArg[:gender] != 'Any' - query = query.where("gender ILIKE ?", searchArg[:gender]) - end - - - if searchArg[:compensation].present? and searchArg[:compensation] != 'Any' - searchArg[:compensation]="%"+searchArg[:compensation]+"%" - query = query.where("compensation ILIKE ?", searchArg[:compensation]) - end - - if searchArg[:job_type].present? and searchArg[:job_type] != 'Any' - query = query.where("job_name ILIKE ?", searchArg[:job_type]) + def self.search(searchArg) + location = searchArg[:location].presence + distance = searchArg[:distance].presence ? Integer(searchArg[:distance]) : 20 + query = location ? GeneralInfo.near(location, distance) : GeneralInfo.all + + query = apply_text_filter(query, searchArg[:first_name], searchArg[:first_name_regex], "first_name") if searchArg[:first_name].present? + query = apply_text_filter(query, searchArg[:last_name], searchArg[:last_name_regex], "last_name") if searchArg[:last_name].present? + + query = apply_direct_filter(query, searchArg[:gender], "gender") if searchArg[:gender].present? && searchArg[:gender] != 'Any' + query = apply_direct_filter(query, searchArg[:compensation], "compensation", wildcard: true) if searchArg[:compensation].present? && searchArg[:compensation] != 'Any' + query = apply_direct_filter(query, searchArg[:job_type], "job_name") if searchArg[:job_type].present? && searchArg[:job_type] != 'Any' + + query + end + + private_class_method def self.apply_text_filter(query, value, regex, column) + case regex + when 'Contains' + value = "%#{value}%" + when 'Starts With' + value = "#{value}%" + when 'Ends With' + value = "%#{value}" + when 'Exactly Matches' + value = value end - - return query + query.where("#{column} ILIKE ?", value) + end + + private_class_method def self.apply_direct_filter(query, value, column, wildcard: false) + value = "%#{value}%" if wildcard + query.where("#{column} ILIKE ?", value) end # Sets appearance of profile view attributes @@ -171,178 +145,146 @@ def self.delete_Job(jobName) end - def self.load_Job_File() + def self.load_Job_File jobString = $redis.get('jobList') - jobArray = Array.new - if(jobString != nil && jobString != "") - jobArray = jobString.scan(/\w+/) - jobArray.each do |job| - attrString = $redis.get(job) - if(attrString != nil) # If there's a redis for this job - eachAttrMatch = attrString.to_enum(:scan, /\w+(\s\w+)*(%)/).map {Regexp.last_match} - eachTypeMatch = attrString.to_enum(:scan, /\w+(\s\w+)*(,|')/).map {Regexp.last_match} # Not really implemented yet, just a copy of the attribute name - eachAttrMatch = eachAttrMatch.flatten - eachTypeMatch = eachTypeMatch.flatten - - self.create_Job(job, false) - if(eachAttrMatch != nil && eachAttrMatch.size > 0) - eachAttrMatch.each do |attr| - job.constantize.add_Attr(attr.to_s.chop, "String", false) # Add the types you get from TypeMatch to further specialize this - end - job.constantize.update_File() - end - end - end - else # Job Redis is empty/ never been used. Initialize Admin role - $redis.set('jobList', '\'Admin\'') - $redis.set('Admin', '') - self.create_Job('Admin', false) + + if jobString.present? + load_jobs_from_redis(jobString) + else + initialize_admin_role end - - #@@Job_List = jobArray - end - - def self.create_Job (className, writeToFile = true) - - # Code to validate the job name has chars only will go here - - if(self.check_Job?(className.upcase_first) == false && className != 'Admin' && className != 'admin') - @@Job_List.push(className.upcase_first) - @@Job_Attr[className.upcase_first] = Array.new - @@Attr_Type[className.upcase_first] = Array.new - - - # Create entry in Job File List - - creator = Object.const_set(className.upcase_first, Class.new { - - - - def self.display_Name() - self.name - end - - #def display_Name() - #self.display_Name() - #end - - # def initialize() - - # end - - def self.add_Attr(attr_Name, attr_Type = "String", writeToRedis = true) - # If Name not in hash already - if(@@Job_Attr[self.name].include?(attr_Name) == false) - @@Job_Attr[self.name].push(attr_Name) - @@Attr_Type[self.name].push(attr_Type) - if(writeToRedis) - self.update_File - end - end - - # Else Error, name already exists - end - - #def add_Attr(attr_Name, attr_Type = "String", writeToRedis = true) - #self.add_Attr(attr_Name, attr_Type, writeToRedis) - #end - - def self.edit_Attr(attr_Name, new_Name, new_Type = nil) - indexLoc = @@Job_Attr[self.name].find_index(attr_Name) - - if(indexLoc) - @@Job_Attr[self.name][indexLoc] = new_Name - if(new_Type != nil) - @@Attr_Type[self.name] = new_Type - end - self.update_File - # Code to run through database and edit all existing entries - end - end - - #def edit_Attr(attr_Name, new_Name, new_Type = nil) - #self.edit_Attr(attr_Name, new_Name, new_Type) - #end - - def self.delete_Attr(attr_Name) - indexLoc = @@Job_Attr[self.name].find_index(attr_Name) - - if(indexLoc) - @@Job_Attr[self.name].delete_at(indexLoc) - @@Attr_Type[self.name].delete_at(indexLoc) - self.update_File - # Code to shift all attributes into place in database is in Admin controller - end - end - - #def delete_Attr(attr_Name) - #self.delete_Attr(attr_Name) - #end - - def self.view_Attr() - @@Job_Attr[self.name] - end - - #def view_Attr() - #self.view_Attr() - #end - - def self.view_Attr_Type(attr_Name = nil) - if (attr_Name == nil) - @@Attr_Type[self.name] - else - indexLoc = @@Attr_Type[self.name].find_index(attr_Name) - - if(indexLoc) - @@Attr_Type[self.name][indexLoc] - else - nil - end - end - end - - #def view_Attr_Type(attr_Name) - #self.view_Attr_Type(attr_Name) - #end - - def self.update_File() - self_Name = self.name - attr_Body = '\'' - x = 0 - while(x < @@Job_Attr[self.name].size) - attr_Body = attr_Body + @@Job_Attr[self.name][x] + '%' + @@Attr_Type[self.name][x] + '\'' - x = x + 1 - end - if(attr_Body == '\'') - attr_Body = '\'\'' - end - # new_line = self.display_Name + " " + attr_Body - # file_cont = File.read ("jobList.dat") - # new_cont = file_cont.gsub(/^(#{Regexp.escape(self_Name)}).*/, new_line) - # File.open("jobList.dat", "w") {|file| file.puts new_cont} - $redis.set(self.name, attr_Body) - end - - #def update_File() - #self.update_File() - #end - - }) - - writeToFile = true - if(writeToFile) - jobString = '\'' - @@Job_List.each do |job| - jobString = jobString + job + '\'' - end - jobString = jobString + className.upcase_first + '\'' - $redis.set('jobList', jobString) - $redis.set(className.upcase_first, '') + + private_class_method def self.load_jobs_from_redis(jobString) + jobArray = jobString.scan(/\w+/) + + jobArray.each do |job| + load_job_attributes(job) + end + end + + private_class_method def self.load_job_attributes(job) + attrString = $redis.get(job) + + return if attrString.nil? + + eachAttrMatch = extract_attributes(attrString) + eachTypeMatch = extract_types(attrString) + + self.create_Job(job, false) + + if eachAttrMatch.any? + eachAttrMatch.each do |attr| + job.constantize.add_Attr(attr.to_s.chop, "String", false) end + job.constantize.update_File end end - + + private_class_method def self.extract_attributes(attrString) + attrString.to_enum(:scan, /\w+(\s\w+)*(%)/).map { Regexp.last_match }.flatten + end + + private_class_method def self.extract_types(attrString) + attrString.to_enum(:scan, /\w+(\s\w+)*(,|')/).map { Regexp.last_match }.flatten + end + + private_class_method def self.initialize_admin_role + $redis.set('jobList', 'Admin') + $redis.set('Admin', '') + self.create_Job('Admin', false) + end + + def self.create_Job(className, writeToFile = true) + # Return early if job already exists or if it's 'Admin' or 'admin' + return if self.check_Job?(className.upcase_first) || className.downcase == 'admin' + + # Initialize job with empty attributes + initialize_job(className) + + # Create the class dynamically + creator = create_job_class(className) + + # Update Redis with the new job list + update_job_list_to_redis(className) if writeToFile + end + + # Initialize the job attributes and list + private_class_method def self.initialize_job(className) + @@Job_List.push(className.upcase_first) + @@Job_Attr[className.upcase_first] = [] + @@Attr_Type[className.upcase_first] = [] + end + + # Dynamically create the job class with the necessary methods + private_class_method def self.create_job_class(className) + Object.const_set(className.upcase_first, Class.new { + # Add methods to the job class + def self.display_Name + self.name + end + + def self.add_Attr(attr_Name, attr_Type = "String", writeToRedis = true) + return if @@Job_Attr[self.name].include?(attr_Name) + + @@Job_Attr[self.name].push(attr_Name) + @@Attr_Type[self.name].push(attr_Type) + + update_File if writeToRedis + end + + def self.edit_Attr(attr_Name, new_Name, new_Type = nil) + indexLoc = @@Job_Attr[self.name].find_index(attr_Name) + return unless indexLoc + + @@Job_Attr[self.name][indexLoc] = new_Name + @@Attr_Type[self.name] = new_Type if new_Type + + update_File + end + + def self.delete_Attr(attr_Name) + indexLoc = @@Job_Attr[self.name].find_index(attr_Name) + return unless indexLoc + + @@Job_Attr[self.name].delete_at(indexLoc) + @@Attr_Type[self.name].delete_at(indexLoc) + + update_File + end + + def self.view_Attr + @@Job_Attr[self.name] + end + + def self.view_Attr_Type(attr_Name = nil) + return @@Attr_Type[self.name] unless attr_Name + + indexLoc = @@Attr_Type[self.name].find_index(attr_Name) + indexLoc ? @@Attr_Type[self.name][indexLoc] : nil + end + + def self.update_File + attr_Body = "'" + build_attr_body + $redis.set(self.name, attr_Body) + end + + private + + def self.build_attr_body + @@Job_Attr[self.name].each_with_index.map do |attr, index| + "#{attr}%#{@@Attr_Type[self.name][index]}" + end.join("'") + end + }) + end + + # Update the job list in Redis + private_class_method def self.update_job_list_to_redis(className) + jobString = @@Job_List.map { |job| "'#{job}'" }.join + $redis.set('jobList', "'#{jobString}'") + $redis.set(className.upcase_first, '') + end def follow(id) followee = GeneralInfo.find(id) @@ -362,39 +304,70 @@ def get_users_they_follow self.follows_others end - def self.filterBy country, state, profession, city - #filter by profession, country, state - @filteredUsers = profession.present? ? GeneralInfo.where(job_name: profession) : GeneralInfo.all - # @filteredUsers = @filteredUsers.where(country: country) #United States - - #@filteredUsers = country.present? ? GeneralInfo.where(country: country) : @filteredUsers - @filteredUsers = country.present? ? @filteredUsers.where(country: country) : @filteredUsers - - @filteredUsers = state.present? ? @filteredUsers.where(state: state) : @filteredUsers - #adding city on filter list - #@filteredUsers = city.present? ? @filteredUsers.where(city: city) : @filteredUsers - @filteredUsers = city.present? ? @filteredUsers.where("LOWER(city) = ?", city.downcase) : @filteredUsers - - - #@filteredUsers.each do |room| - # puts "users are: #{room[:first_name]}" - #end - - - # add travel feature - # if the profession travels to the city within 30 days, - # he should show up in the search results - @filteredUsers1 = profession.present? ? GeneralInfo.where(job_name: profession) : GeneralInfo.all - @filteredUsers1 = country.present? ? @filteredUsers1.where(travel_country: country) : @filteredUsers1 - @filteredUsers1 = state.present? ? @filteredUsers1.where(travel_state: state) : @filteredUsers1 - @filteredUsers1 = city.present? ? @filteredUsers1.where(travel_city: city) : @filteredUsers1 - # @filteredUsers1 = @filteredUsers1.where(travel_start: Date.today..30.days.from_now.to_date) + \ - # @filteredUsers1.where.not(travel_start: Date.today..30.days.from_now.to_date). - @filteredUsers1 = @filteredUsers1.where(travel_start: Date.today..30.days.from_now.to_date)\ - .or(@filteredUsers1.where(travel_end: Date.today..30.days.from_now.to_date)\ - .or(@filteredUsers1.where('travel_start < ?', Date.today).where('travel_end > ?', Date.today) ) ) - - return @filteredUsers.or(@filteredUsers1) + def self.filterBy(country, state, profession, city) + filtered_by_profession = filter_by_profession(profession) + filtered_by_country = filter_by_country(filtered_by_profession, country) + filtered_by_state = filter_by_state(filtered_by_country, state) + filtered_by_city = filter_by_city(filtered_by_state, city) + + filtered_by_travel = filter_by_travel(profession, country, state, city) + + return filtered_by_city.or(filtered_by_travel) end -end - + + # Helper method to filter by profession + private_class_method def self.filter_by_profession(profession) + profession.present? ? GeneralInfo.where(job_name: profession) : GeneralInfo.all + end + + # Helper method to filter by country + private_class_method def self.filter_by_country(filtered_users, country) + country.present? ? filtered_users.where(country: country) : filtered_users + end + + # Helper method to filter by state + private_class_method def self.filter_by_state(filtered_users, state) + state.present? ? filtered_users.where(state: state) : filtered_users + end + + # Helper method to filter by city + private_class_method def self.filter_by_city(filtered_users, city) + city.present? ? filtered_users.where("LOWER(city) = ?", city.downcase) : filtered_users + end + + # Helper method to filter by travel attributes + private_class_method def self.filter_by_travel(profession, country, state, city) + filtered_users1 = profession.present? ? GeneralInfo.where(job_name: profession) : GeneralInfo.all + filtered_users1 = filter_by_travel_country(filtered_users1, country) + filtered_users1 = filter_by_travel_state(filtered_users1, state) + filtered_users1 = filter_by_travel_city(filtered_users1, city) + + filtered_users1 = filter_by_travel_dates(filtered_users1) + + filtered_users1 + end + + # Helper method to filter by travel country + private_class_method def self.filter_by_travel_country(filtered_users1, country) + country.present? ? filtered_users1.where(travel_country: country) : filtered_users1 + end + + # Helper method to filter by travel state + private_class_method def self.filter_by_travel_state(filtered_users1, state) + state.present? ? filtered_users1.where(travel_state: state) : filtered_users1 + end + + # Helper method to filter by travel city + private_class_method def self.filter_by_travel_city(filtered_users1, city) + city.present? ? filtered_users1.where(travel_city: city) : filtered_users1 + end + + # Helper method to filter by travel dates + private_class_method def self.filter_by_travel_dates(filtered_users1) + filtered_users1.where(travel_start: Date.today..30.days.from_now.to_date) + .or(filtered_users1.where(travel_end: Date.today..30.days.from_now.to_date)) + .or(filtered_users1.where('travel_start < ?', Date.today) + .where('travel_end > ?', Date.today)) + end + +end \ No newline at end of file diff --git a/app/models/specific_model.rb b/app/models/specific_model.rb index a9273156e..06910588f 100644 --- a/app/models/specific_model.rb +++ b/app/models/specific_model.rb @@ -1,158 +1,108 @@ - class SpecificModel < ApplicationRecord - attr_accessor :allgenres - - #params_arg are the params returned from the SpecificModel search but DOES NOT INCLUDE GENRE - def self.search params_arg - @final_return = [] - - if params_arg.length > 0 - GeneralInfo.all.find_each do |user_object| - - if user_object[:specific_profile_id] == 2 - spec_object = SpecificModel.find_by(user_key: user_object["userKey"]) - puts spec_object.inspect - - incl = true - params_arg.each do |param_key, param_val| - if param_key == "checkboxes" || param_key == "min_dress_size" - next - end - - if param_key == "max_height" || param_key == "min_height" - model_height_ft = 0 - model_height_in = 0 - - if spec_object["height_feet"] != nil - model_height_ft = spec_object["height_feet"] - end - - if spec_object["height_inches"] != nil - model_height_in = spec_object["height_inches"] - end - - model_height_tot = (model_height_ft * 12) + model_height_in - - min_height = 0 - max_height = 99999 - - if params_arg.include? "min_height" - min_height = params_arg["min_height"].to_f - end - - if params_arg.include? "max_height" - max_height = params_arg["max_height"].to_f - end - - if model_height_tot < (min_height * 12) || model_height_tot > (max_height * 12) - incl = false - end - - if model_height_tot == 0 - incl = false - end - elsif param_key == "max_dress_size" || param_key == "min_dress_size" - model_dress_size = 0 - - if spec_object["dress_size"] != nil - model_dress_size = spec_object["dress_size"] - end - - min_size = 0 - max_size = 99999 - if params_arg.include? "min_dress_size" - min_size = params_arg["min_dress_size"].to_i - end - - if params_arg.include? "max_dress_size" - max_size = params_arg["max_dress_size"].to_i - end - - puts min_size - puts max_size - puts model_dress_size - if model_dress_size < min_size || model_dress_size > max_size - incl = false - end - - if model_dress_size == 0 - incl = false - end - else - - chk_val = user_object[param_key] - - if chk_val == nil - puts param_key - chk_val = spec_object[param_key] - end - - if chk_val != param_val - incl = false - end - end - end - - # GENRE CHECKING - - if params_arg["checkboxes"] && incl && spec_object["genre"] - genre_arr = spec_object["genre"].split(",") - - puts genre_arr - - genre_incl = false - params_arg["checkboxes"].each do |genre| - if genre_arr.include? genre - puts genre - genre_incl = true - end - end - - incl = genre_incl - end - - if incl - @final_return.push(user_object[:userKey]) - end - end - end - else - GeneralInfo.all.find_each do |user_object| - if user_object[:specific_profile_id] == 2 - @final_return.push(user_object[:userKey]) - end - end - end - - return @final_return - end - - # Sets appearance of profile view attributes - def attribute_values - @attribute_values = Hash.new - @attribute_values[:height] = "Height: " + self.height_feet.to_s + " ft. " + self.height_inches.to_s + " in." - @attribute_values[:bust] = "Bust size: " + self.bust.to_s + " in." - @attribute_values[:waist] = "Waist size: " + self.bust.to_s + " in." - @attribute_values[:hips] = "Hips size: " + self.hips.to_s + " in." - @attribute_values[:cups] = "Cup size: " + self.cups.to_s - @attribute_values[:shoe_size] = "Shoe size: " + self.shoe_size.to_s - @attribute_values[:dress_size] = "Dress size: " + self.dress_size.to_s - @attribute_values[:hair_color] = "Hair color: " + self.hair_color.to_s - @attribute_values[:eye_color] = "Eye color: " + self.eye_color.to_s - @attribute_values[:ethnicity] = "Ethnicity: " + self.ethnicity.to_s - @attribute_values[:skin_color] = "Skin color: " + self.skin_color.to_s - @attribute_values[:shoot_nudes] = "Shoots nudes: " + self.shoot_nudes.to_s - @attribute_values[:tattoos] = "Has tattoos: " + self.tattoos.to_s - @attribute_values[:piercings] = "Piercings: " + self.piercings.to_s - @attribute_values[:experience] = "Experience: " + self.experience.to_s - - @attribute_values[:genre] = "Genre: " - if self.genre != nil - self.genre.split(",").each do |genre| - @attribute_values[:genre] += genre + ", " - end - @attribute_values[:genre] = @attribute_values[:genre][0, @attribute_values[:genre].length-2] - end - - @attribute_values - end - end +class SpecificModel < ApplicationRecord + attr_accessor :allgenres + + def self.search(params_arg) + @final_return = [] + + if params_arg.length > 0 + GeneralInfo.all.find_each do |user_object| + next unless user_object[:specific_profile_id] == 2 + + spec_object = SpecificModel.find_by(user_key: user_object["userKey"]) + next unless spec_object + + incl = validate_params(params_arg, user_object, spec_object) + incl &&= genre_check(params_arg["checkboxes"], spec_object["genre"]) if params_arg["checkboxes"] + + @final_return.push(user_object[:userKey]) if incl + end + else + find_all_users + end + + @final_return + end + + # Validate params other than genre + def self.validate_params(params_arg, user_object, spec_object) + params_arg.each do |param_key, param_val| + next if ["checkboxes", "min_dress_size"].include?(param_key) + + case param_key + when "max_height", "min_height" + return false unless validate_height(params_arg, spec_object) + when "max_dress_size", "min_dress_size" + return false unless validate_dress_size(params_arg, spec_object) + else + chk_val = user_object[param_key] || spec_object[param_key] + return false if chk_val != param_val + end + end + true + end + + # Validate height range + def self.validate_height(params_arg, spec_object) + model_height = (spec_object["height_feet"].to_i * 12) + spec_object["height_inches"].to_i + return false if model_height.zero? + + min_height = params_arg["min_height"].to_f * 12 || 0 + max_height = params_arg["max_height"].to_f * 12 || Float::INFINITY + model_height.between?(min_height, max_height) + end + + # Validate dress size range + def self.validate_dress_size(params_arg, spec_object) + model_dress_size = spec_object["dress_size"].to_i + return false if model_dress_size.zero? + + min_size = params_arg["min_dress_size"].to_i || 0 + max_size = params_arg["max_dress_size"].to_i || Float::INFINITY + model_dress_size.between?(min_size, max_size) + end + + # Validate genres + def self.genre_check(checkboxes, genre_string) + return false unless genre_string + + genre_arr = genre_string.split(",") + checkboxes.any? { |genre| genre_arr.include?(genre) } + end + + # Find all users with specific_profile_id == 2 + def self.find_all_users + GeneralInfo.all.find_each do |user_object| + @final_return.push(user_object[:userKey]) if user_object[:specific_profile_id] == 2 + end + end + + # Sets appearance of profile view attributes + def attribute_values + @attribute_values = { + height: "Height: #{height_feet} ft. #{height_inches} in.", + bust: "Bust size: #{bust} in.", + waist: "Waist size: #{waist} in.", + hips: "Hips size: #{hips} in.", + cups: "Cup size: #{cups}", + shoe_size: "Shoe size: #{shoe_size}", + dress_size: "Dress size: #{dress_size}", + hair_color: "Hair color: #{hair_color}", + eye_color: "Eye color: #{eye_color}", + ethnicity: "Ethnicity: #{ethnicity}", + skin_color: "Skin color: #{skin_color}", + shoot_nudes: "Shoots nudes: #{shoot_nudes}", + tattoos: "Has tattoos: #{tattoos}", + piercings: "Piercings: #{piercings}", + experience: "Experience: #{experience}", + genre: format_genres + } + end + + # Format genres + def format_genres + return "Genre: " unless genre + + genres = genre.split(",").join(", ") + "Genre: #{genres}" + end +end From d20f54426b2d2282e8faa87bd1f338e40d40269a Mon Sep 17 00:00:00 2001 From: Maikanta Gudipudi Date: Fri, 22 Nov 2024 03:53:55 -0600 Subject: [PATCH 3/4] error fixed --- app/controllers/admin/admin_controller.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/controllers/admin/admin_controller.rb b/app/controllers/admin/admin_controller.rb index c27f5069b..89ee5a307 100644 --- a/app/controllers/admin/admin_controller.rb +++ b/app/controllers/admin/admin_controller.rb @@ -6,7 +6,9 @@ class AdminController < ApplicationController def landing @hasPermission = check_admin_permission - redirect_to "/login_info/login" unless @hasPermission + if(@hasPermission == false) + redirect_to "/login_info/login" + end end def create From 06ff446dc4a47a7731f25a65582658b08efb78c0 Mon Sep 17 00:00:00 2001 From: Maikanta Gudipudi Date: Fri, 22 Nov 2024 04:06:00 -0600 Subject: [PATCH 4/4] fixed errors in admin_controller --- app/controllers/admin/admin_controller.rb | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/app/controllers/admin/admin_controller.rb b/app/controllers/admin/admin_controller.rb index 89ee5a307..5f4a67071 100644 --- a/app/controllers/admin/admin_controller.rb +++ b/app/controllers/admin/admin_controller.rb @@ -30,8 +30,9 @@ def create def edit @hasPermission = check_admin_permission - redirect_to "/login_info/login" unless @hasPermission - + if @hasPermission == false + redirect_to "/login_info/login" + end @jobs = GeneralInfo.see_Jobs.map(&:titleize) if params[:job_name].present? && params[:attr_action].present? && params[:attr_name].present? @@ -52,7 +53,9 @@ def edit def delete @hasPermission = check_admin_permission - redirect_to "/login_info/login" unless @hasPermission + if @hasPermission == false + redirect_to "/login_info/login" + end @jobs = GeneralInfo.see_Jobs.map(&:titleize)