From 3b3e1af822cec6b9ed51c105e0eab6f1dbbdf3fa Mon Sep 17 00:00:00 2001 From: Sylvain Date: Mon, 8 Apr 2019 11:00:00 +0200 Subject: [PATCH] improved coupon filtering to allow pagination while filtering --- app/controllers/api/coupons_controller.rb | 9 ++------- app/models/coupon.rb | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/app/controllers/api/coupons_controller.rb b/app/controllers/api/coupons_controller.rb index 08496abc5..3d7b37703 100644 --- a/app/controllers/api/coupons_controller.rb +++ b/app/controllers/api/coupons_controller.rb @@ -10,13 +10,8 @@ class API::CouponsController < API::ApiController COUPONS_PER_PAGE = 10 def index - if params[:filter] == 'all' - @coupons = Coupon.page(params[:page]).per(COUPONS_PER_PAGE).order('created_at DESC') - @total = Coupon.count - else - @coupons = Coupon.order('created_at DESC').all.select { |c| c.status == params[:filter] } - @total = @coupons.count - end + @coupons = Coupon.method(params[:filter]).call.page(params[:page]).per(COUPONS_PER_PAGE).order('created_at DESC') + @total = Coupon.method(params[:filter]).call.length end def show; end diff --git a/app/models/coupon.rb b/app/models/coupon.rb index 5208cabed..25855cf1e 100644 --- a/app/models/coupon.rb +++ b/app/models/coupon.rb @@ -16,6 +16,20 @@ class Coupon < ActiveRecord::Base validates_with CouponDiscountValidator validates_with CouponExpirationValidator + scope :disabled, -> { where(active: false) } + scope :expired, -> { where('valid_until IS NOT NULL AND valid_until < ?', DateTime.now) } + scope :sold_out, lambda { + joins(:invoices).select('coupons.*, COUNT(invoices.id) as invoices_count').group('coupons.id') + .where.not(max_usages: nil).having('COUNT(invoices.id) >= coupons.max_usages') + } + scope :active, lambda { + joins('LEFT OUTER JOIN invoices ON invoices.coupon_id = coupons.id') + .select('coupons.*, COUNT(invoices.id) as invoices_count') + .group('coupons.id') + .where('active = true AND (valid_until IS NULL OR valid_until >= ?)', DateTime.now) + .having('COUNT(invoices.id) < coupons.max_usages OR coupons.max_usages IS NULL') + } + def safe_destroy if invoices.size.zero? destroy