diff --git a/app/controllers/orders_controller.rb b/app/controllers/orders_controller.rb index 69d4c55..c8a56ca 100644 --- a/app/controllers/orders_controller.rb +++ b/app/controllers/orders_controller.rb @@ -28,6 +28,17 @@ class OrdersController < ApplicationController end end + def destroy + order = Order.find(params[:id]) + if order.created_at > 5.minutes.ago + order.destroy + flash[:success] = "Order has been removed." + else + flash[:error] = "This order has been placed too long ago, it can't be removed. Please contact a sysadmin." + end + redirect_to koelkast_root_path + end + def overview @users_by_name = User.members.order(:name) @users_by_order = User.members.order(:orders_count).reverse_order @@ -38,7 +49,7 @@ class OrdersController < ApplicationController order = user.orders.build order.products << user.dagschotel if order.save - flash[:success] = "Quick pay succeeded" + flash[:success] = "Quick pay succeeded. #{view_context.link_to("Undo", [user, order], method: :delete)}." else flash[:error] = order.errors.full_messages.first end diff --git a/app/models/order.rb b/app/models/order.rb index 72d9416..24916d3 100644 --- a/app/models/order.rb +++ b/app/models/order.rb @@ -14,9 +14,10 @@ class Order < ActiveRecord::Base after_initialize { self.total_price = 0 } after_create { self.user.pay(price) } + before_destroy { self.user.pay(-price) } belongs_to :user, counter_cache: true - has_many :order_products + has_many :order_products, dependent: :destroy has_many :products, through: :order_products attr_accessor :total_price diff --git a/app/models/order_product.rb b/app/models/order_product.rb index 76cf458..eaa2c7d 100644 --- a/app/models/order_product.rb +++ b/app/models/order_product.rb @@ -10,6 +10,7 @@ class OrderProduct < ActiveRecord::Base after_create :remove_from_stock + before_destroy :put_back_in_stock belongs_to :order belongs_to :product @@ -30,4 +31,9 @@ class OrderProduct < ActiveRecord::Base product.stock -= self.count product.save end + + def put_back_in_stock + product.stock += self.count + product.save + end end diff --git a/app/views/application/_flash.html.erb b/app/views/application/_flash.html.erb index 312b24d..6ff50c6 100644 --- a/app/views/application/_flash.html.erb +++ b/app/views/application/_flash.html.erb @@ -8,7 +8,7 @@ <% if flash[:success] %>