Create enterprise model, integrate functionality from supplier

This commit is contained in:
Rohan Mitchell
2012-10-28 13:24:26 +11:00
parent ff24149195
commit c700d9e71b
4 changed files with 83 additions and 1 deletions

32
app/models/enterprise.rb Normal file
View File

@@ -0,0 +1,32 @@
class Enterprise < ActiveRecord::Base
has_many :supplied_products, :class_name => 'Spree::Product', :foreign_key => 'supplier_id'
belongs_to :address, :class_name => 'Spree::Address'
accepts_nested_attributes_for :address
validates_presence_of :name, :address
validates_associated :address
after_initialize :initialize_country
before_validation :set_unused_address_fields
def has_supplied_products_on_hand?
self.supplied_products.where('count_on_hand > 0').present?
end
def to_param
"#{id}-#{name.parameterize}"
end
private
def initialize_country
self.address ||= Spree::Address.new
self.address.country = Spree::Country.find_by_id(Spree::Config[:default_country_id]) if self.address.new_record?
end
def set_unused_address_fields
address.firstname = address.lastname = address.phone = 'unused' if address.present?
end
end

View File

@@ -1,5 +1,5 @@
Spree::Product.class_eval do
belongs_to :supplier
belongs_to :supplier, :class_name => 'Enterprise'
has_many :product_distributions, :dependent => :destroy
has_many :distributors, :through => :product_distributions

View File

@@ -2,6 +2,19 @@ require 'faker'
require 'spree/core/testing_support/factories'
FactoryGirl.define do
factory :enterprise, :class => Enterprise do
sequence(:name) { |n| "Enterprise #{n}" }
description 'enterprise'
long_description '<p>Hello, world!</p><p>This is a paragraph.</p>'
email 'enterprise@example.com'
address { Spree::Address.first || FactoryGirl.create(:address) }
end
factory :supplier_enterprise, :parent => :enterprise do
is_primary_producer true
is_distributor false
end
factory :supplier, :class => Supplier do
sequence(:name) { |n| "Supplier #{n}" }
description 'supplier'

View File

@@ -0,0 +1,37 @@
require 'spec_helper'
describe Enterprise do
describe "associations" do
it { should have_many(:supplied_products) }
it { should belong_to(:address) }
end
describe "validations" do
it { should validate_presence_of(:name) }
end
it "should default country to system country" do
subject.address.country.should == Spree::Country.find_by_id(Spree::Config[:default_country_id])
end
context "has_supplied_products_on_hand?" do
before :each do
@supplier = create(:supplier_enterprise)
end
it "returns false when no products" do
@supplier.should_not have_supplied_products_on_hand
end
it "returns false when the product is out of stock" do
create(:product, :supplier => @supplier, :on_hand => 0)
@supplier.should_not have_supplied_products_on_hand
end
it "returns true when the product is in stock" do
create(:product, :supplier => @supplier, :on_hand => 1)
@supplier.should have_supplied_products_on_hand
end
end
end