diff --git a/app/controllers/classified_listings_controller.rb b/app/controllers/classified_listings_controller.rb index 7b3065cff..2fc27c55e 100644 --- a/app/controllers/classified_listings_controller.rb +++ b/app/controllers/classified_listings_controller.rb @@ -30,26 +30,32 @@ class ClassifiedListingsController < ApplicationController def create @classified_listing = ClassifiedListing.new(classified_listing_params) @classified_listing.user_id = current_user.id - number_of_credits_needed = ClassifiedListing.cost_by_category(@classified_listing.category) - available_credits = current_user.credits.where(spent: false) - if available_credits.size >= number_of_credits_needed - @classified_listing.bumped_at = Time.current - @classified_listing.published = true - @classified_listing.organization_id = current_user.organization_id if @classified_listing.post_as_organization.to_i == 1 - if @classified_listing.save - clear_listings_cache - available_credits.limit(number_of_credits_needed).update_all(spent: true) - @classified_listing.index! - redirect_to "/listings" - else - @credits = current_user.credits.where(spent: false) - render :new - end + @number_of_credits_needed = ClassifiedListing.cost_by_category(@classified_listing.category) + @org = Organization.find(current_user.organization_id) if @classified_listing.post_as_organization.to_i == 1 + available_org_credits = @org.credits.where(spent: false) if @org + available_individual_credits = current_user.credits.where(spent: false) + + if @org && available_org_credits.size >= @number_of_credits_needed + create_listing(available_org_credits) + elsif available_individual_credits.size >= @number_of_credits_needed + create_listing(available_individual_credits) else redirect_to "/credits" end end + def create_listing(credits) + @classified_listing.bumped_at = Time.current + @classified_listing.published = true + @classified_listing.organization_id = current_user.organization_id if @org + return unless @classified_listing.save + + clear_listings_cache + credits.limit(@number_of_credits_needed).update_all(spent: true) + @classified_listing.index! + redirect_to "/listings" + end + def update authorize @classified_listing available_credits = current_user.credits.where(spent: false)