require 'subj_models/concerns/comprising_external_id' require 'subj_models/services/values_checker' require 'subj_models/services/types_support' module SubjModels module Order 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 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 :last_order, -> (user_id) do Order.joins(:user).where("users.id" => user_id).last end end end def to_s id.to_s # TODO end def order_status=(value) super(check_string_for_int(value)) end def delivery_type=(value) super(check_string_for_int(value)) end def payment_type=(value) super(check_string_for_int(value)) 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