1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-03-21 12:29:03 +01:00

(feat) cannot delete a product if it is used in order

This commit is contained in:
Du Peng 2022-09-19 15:20:42 +02:00
parent 034b6b478e
commit e2b6267924
4 changed files with 21 additions and 3 deletions

View File

@ -40,7 +40,7 @@ class API::ProductsController < API::ApiController
def destroy
authorize @product
@product.destroy
ProductService.destroy(@product)
head :no_content
end

View File

@ -0,0 +1,3 @@
# Raised when delete a product if this product has used in order
class CannotDeleteProductError < StandardError
end

View File

@ -7,10 +7,10 @@ class Checkout::PaymentService
include Payments::PaymentConcern
def payment(order, operator, coupon_code, payment_id = '')
raise Cart::OutStockError unless Orders::OrderService.new.in_stock?(order, 'external')
raise Cart::InactiveProductError unless Orders::OrderService.new.all_products_is_active?(order)
raise Cart::OutStockError unless Orders::OrderService.new.in_stock?(order, 'external')
CouponService.new.validate(coupon_code, order.statistic_profile.user.id)
amount = debit_amount(order)

View File

@ -64,5 +64,20 @@ class ProductService
update_stock(product, stock_movement_params)
product
end
def destroy(product)
used_in_order = OrderItem.joins(:order).where.not('orders.state' => 'cart')
.exists?(orderable: product)
raise CannotDeleteProductError if used_in_order
ActiveRecord::Base.transaction do
orders_with_product = Order.joins(:order_items).where(state: 'cart').where('order_items.orderable': product)
orders_with_product.each do |order|
::Cart::RemoveItemService.new.call(order, product)
end
product.destroy
end
end
end
end