diff --git a/app/controllers/product_drives_controller.rb b/app/controllers/product_drives_controller.rb index 05e55e5dca..c7be796378 100644 --- a/app/controllers/product_drives_controller.rb +++ b/app/controllers/product_drives_controller.rb @@ -76,10 +76,13 @@ def update end def destroy - current_organization.product_drives.find(params[:id]).destroy - respond_to do |format| - format.html { redirect_to product_drives_url, notice: 'Product drive was successfully destroyed.' } - format.json { head :no_content } + result = ProductDriveDestroyService.call(@product_drive, current_user, current_organization) + + if result.success? + redirect_to product_drives_url, notice: result.value + else + flash[:error] = result.error + redirect_back(fallback_location: product_drives_url) end end diff --git a/app/services/product_drive_destroy_service.rb b/app/services/product_drive_destroy_service.rb new file mode 100644 index 0000000000..ea6533bc90 --- /dev/null +++ b/app/services/product_drive_destroy_service.rb @@ -0,0 +1,29 @@ +class ProductDriveDestroyService + class << self + def call(product_drive, user, organization) + return Result.new(error: "You are not allowed to perform this action.") unless verify_role(user, organization) + + unless can_destroy?(product_drive, user) + product_drive.errors.add(:base, "Cannot delete product drive with donations.") + raise ActiveRecord::RecordInvalid.new(product_drive) + end + + if product_drive.destroy + Result.new(value: "Product drive was successfully destroyed.") + else + raise ActiveRecord::RecordNotDestroyed.new("Failed to destroy product drive", product_drive) + end + end + + def can_destroy?(product_drive, user) + return false unless user.has_role?(Role::ORG_ADMIN, product_drive.organization) + product_drive.donations.empty? + end + + private + + def verify_role(user, organization) + user.has_role?(Role::ORG_ADMIN, organization) + end + end +end diff --git a/app/views/product_drives/show.html.erb b/app/views/product_drives/show.html.erb index 4153457f04..906c925cf4 100644 --- a/app/views/product_drives/show.html.erb +++ b/app/views/product_drives/show.html.erb @@ -90,7 +90,7 @@