1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-29 18:52:22 +01:00

improved coupon filtering to allow pagination while filtering

This commit is contained in:
Sylvain 2019-04-08 11:00:00 +02:00
parent 44479b5597
commit 3b3e1af822
2 changed files with 16 additions and 7 deletions

View File

@ -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

View File

@ -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