Sha256: 964c16aa66fac298ab0d38abdf00f93883bdd67d35f079cacd4bd8c2792886e2

Contents?: true

Size: 1.65 KB

Versions: 2

Compression:

Stored size: 1.65 KB

Contents

module Spree
  class LoyaltyPointsTransaction < ActiveRecord::Base
    include Spree::TransactionsTotalValidation
    TRANSACTION_TYPES = ['Spree::LoyaltyPointsCreditTransaction', 'Spree::LoyaltyPointsDebitTransaction']
    CLASS_TO_TRANSACTION_TYPE = { 'Spree::LoyaltyPointsCreditTransaction' => 'Credit', 'Spree::LoyaltyPointsDebitTransaction' => 'Debit'}
    belongs_to :user
    belongs_to :source, polymorphic: true

    validates :loyalty_points, :numericality => { :only_integer => true, :message => Spree.t('validation.must_be_int'), :greater_than => 0 }
    validates :type, inclusion: { in: TRANSACTION_TYPES }
    validates :balance, presence: true
    validate :source_or_comment_present
    validate :transactions_total_range, if: -> { source.present? && source.loyalty_points_transactions.present? }

    #TODO -> rspecs missing for this scope
    scope :for_order, ->(order) { where(source: order) }

    #TODO -> Rspecs missing for this callback.
    before_create :generate_transaction_id

    #TODO -> Rspecs missing for this method.
    def transaction_type
      CLASS_TO_TRANSACTION_TYPE[type]
    end

    private

      def source_or_comment_present
        unless source.present? || comment.present?
          errors.add :base, 'Source or Comment should be present'
        end
      end

      def generate_transaction_id
        begin
          self.transaction_id = (Time.current.strftime("%s") + rand(999999).to_s).to(15)
        end while Spree::LoyaltyPointsTransaction.where(:transaction_id => transaction_id).present? 
      end

      def transactions_total_range
        validate_transactions_total_range(transaction_type, source)
      end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
spree_loyalty_points-1.0.1 app/models/spree/loyalty_points_transaction.rb
spree_loyalty_points-1.0.0 app/models/spree/loyalty_points_transaction.rb