Sha256: 6245aab942b26798ce014c5f8d26d0a0519275a5177fb32307e503fa2d9de274

Contents?: true

Size: 1.11 KB

Versions: 62

Compression:

Stored size: 1.11 KB

Contents

module Workarea
  module Tax
    class Category
      include ApplicationDocument

      field :name, type: String
      field :code, type: String

      index({ code: 1 }, { unique: true })

      has_many :rates, class_name: 'Workarea::Tax::Rate'

      validates :name, presence: true
      validates :code, presence: true, uniqueness: true

      after_save :expire_code_cache

      def self.find_by_code(code)
        Rails.cache.fetch("tax_rate_#{code}", expires_in: Workarea.config.cache_expirations.tax_rate_by_code) do
          find_by(code: code) rescue nil
        end
      end

      def find_rate(price, country, region, postal_code)
        RateLookup.find_best_rate(
          price: price,
          country: country,
          region: region,
          postal_code: postal_code,
          category: self
        )
      end

      def tiered?
        @tiered ||= rates.or(
          { :'tier_min.cents'.exists => true },
          { :'tier_max.cents'.exists => true }
        ).exists?
      end

      private

      def expire_code_cache
        Rails.cache.delete("tax_rate_#{code}")
      end
    end
  end
end

Version data entries

62 entries across 62 versions & 1 rubygems

Version Path
workarea-core-3.4.13 app/models/workarea/tax/category.rb
workarea-core-3.4.12 app/models/workarea/tax/category.rb