require 'subj_models/concerns/comprising_external_id' require 'subj_models/services/values_checker' require 'subj_models/services/types_support' module SubjModels module OrderModule include SubjModels::TypesSupport::OrderStatuses include SubjModels::TypesSupport::DeliveryTypes include SubjModels::TypesSupport::PaymentTypes include SubjModels::ValuesChecker def self.included(including_class) including_class.class_eval do before_create :generate_number include SubjModels::ComprisingExternalId enum order_status: ORDER_STATUSES enum delivery_type: DELIVERY_TYPES enum payment_type: PAYMENT_TYPES belongs_to :user belongs_to :user_delivery_address has_one :order_delivery_courier has_one :order_delivery_pickup has_one :order_delivery_privatbank has_one :order_delivery_subj_courier has_one :order_delivery_nova_poshta_warhouse has_many :order_items, dependent: :destroy has_many :event_bookings validates :order_status, inclusion: { in: order_statuses.keys }, on: :update validates :delivery_type, inclusion: { in: delivery_types.keys }, on: :update validates :payment_type, inclusion: { in: payment_types.keys }, on: :update validates :total_amount, :order_date, presence: true, on: :update scope :user_id, -> user { where(user_id: user) } scope :with_status, -> (status) do where(order_status: Order.order_statuses[status] || status) end scope :last_order, -> (user_id) do Order.joins(:user, :order_items) .where("users.id" => user_id) .where(order_items: {item_type: 1}) .last end scope :has_items, -> { joins(:order_items).where.not(order_items: {order_id: nil}).uniq } end end def order_status_value self[:order_status] end def delivery_type_value self[:delivery_type] end def payment_type_value self[:payment_type] end def to_s id.to_s # TODO end private def generate_number begin self.order_number = "#{Time.now.strftime('%m')}-#{Time.now.strftime('%S%L')}#{rand(100..999)}" end while self.class.exists?(order_number: order_number) end end end