2016-08-03 17:56:36 +02:00
|
|
|
class API::CouponsController < API::ApiController
|
|
|
|
before_action :authenticate_user!
|
|
|
|
before_action :set_coupon, only: [:show, :update, :destroy]
|
|
|
|
|
|
|
|
def index
|
|
|
|
@coupons = Coupon.all
|
|
|
|
end
|
|
|
|
|
|
|
|
def show
|
|
|
|
end
|
|
|
|
|
|
|
|
def create
|
|
|
|
authorize Coupon
|
|
|
|
@coupon = Coupon.new(coupon_params)
|
|
|
|
if @coupon.save
|
|
|
|
render :show, status: :created, location: @coupon
|
|
|
|
else
|
|
|
|
render json: @coupon.errors, status: :unprocessable_entity
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-08-08 14:42:17 +02:00
|
|
|
def validate
|
|
|
|
@coupon = Coupon.find_by_code(params[:code])
|
|
|
|
if @coupon.nil?
|
|
|
|
render json: {status: 'rejected'}, status: :not_found
|
|
|
|
else
|
2016-08-08 15:21:33 +02:00
|
|
|
status = @coupon.status
|
|
|
|
if status != 'active'
|
2016-08-08 15:43:02 +02:00
|
|
|
render json: {status: status}, status: :unprocessable_entity
|
2016-08-08 15:21:33 +02:00
|
|
|
else
|
|
|
|
render :validate, status: :ok, location: @coupon
|
|
|
|
end
|
2016-08-08 14:42:17 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-08-03 17:56:36 +02:00
|
|
|
def update
|
|
|
|
authorize Coupon
|
2016-08-08 15:21:33 +02:00
|
|
|
if @coupon.update(coupon_editable_params)
|
2016-08-03 17:56:36 +02:00
|
|
|
render :show, status: :ok, location: @coupon
|
|
|
|
else
|
|
|
|
render json: @coupon.errors, status: :unprocessable_entity
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def destroy
|
|
|
|
authorize Coupon
|
2016-08-08 12:25:27 +02:00
|
|
|
if @coupon.safe_destroy
|
|
|
|
head :no_content
|
|
|
|
else
|
|
|
|
head :unprocessable_entity
|
|
|
|
end
|
2016-08-03 17:56:36 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
def set_coupon
|
|
|
|
@coupon = Coupon.find(params[:id])
|
|
|
|
end
|
|
|
|
|
|
|
|
def coupon_params
|
2016-08-08 14:42:17 +02:00
|
|
|
params.require(:coupon).permit(:name, :code, :percent_off, :validity_per_user, :valid_until, :max_usages, :active)
|
2016-08-03 17:56:36 +02:00
|
|
|
end
|
2016-08-08 15:21:33 +02:00
|
|
|
|
|
|
|
def coupon_editable_params
|
|
|
|
params.require(:coupon).permit(:name, :active)
|
|
|
|
end
|
2016-08-03 17:56:36 +02:00
|
|
|
end
|