Skip to content

Commit

Permalink
Make the send orders webhook work
Browse files Browse the repository at this point in the history
Currently taking forever to process /add_order .. code needs some major
dedesign
  • Loading branch information
huoxito committed Dec 16, 2014
1 parent e36d555 commit 939ceac
Show file tree
Hide file tree
Showing 10 changed files with 71 additions and 162 deletions.
4 changes: 2 additions & 2 deletions lib/SF_services/account.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ def initialize(config)
end

def find_account_id_by_email(email)
results = salesforce.query("select Id from Account where PersonEmail = '#{email}'")
results.any? ? results.first['Account__c'] : nil
results = salesforce.query("SELECT Contact.Account.Id FROM Contact WHERE Email = '#{email}'")
results.any? ? results.first['Account']['Id'] : nil
end
end
end
51 changes: 44 additions & 7 deletions lib/SF_services/line_item.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ def find_order(order_code)
results.any? ? results.first['Id'] : nil
end

def find_product(product_code)
results = salesforce.query("select Id from PricebookEntry where ProductCode = '#{product_code}'")
results.any? ? results.first['Id'] : nil
def find_pricebook_entry(standard_id, product_id)
filter = "where Pricebook2Id = '#{standard_id}' and Product2Id = '#{product_id}'"
results = salesforce.query "select Id, IsActive from PricebookEntry #{filter}"
results.first
end

def find_line_item(order_id, product_id)
Expand All @@ -22,11 +23,47 @@ def find_line_item(order_id, product_id)

def upsert!(line_item_attr = {}, order_code, product_code)
order_id = find_order(order_code)
product_id = find_product(product_code)
line_item_id = find_line_item(order_id, product_id)

line_item_attr = [line_item_attr, { 'OpportunityId' => order_id }, { 'PricebookEntryId' => product_id }].reduce &:merge
line_item_id.present? ? update!(line_item_attr.merge({ Id: line_item_id })) : create!(line_item_attr)
# FIXME product ids are already fetched before on the stack
results = salesforce.query("select Id from Product2 where ProductCode = '#{product_code}'")
raise SalesfoceIntegrationError, "Product #{product_code} not found" unless results.first

product_id = results.first["Id"]

# FIXME same here standard price book id is already fetched before
unless standard = salesforce.query("select Id from Pricebook2 where isStandard=true").first
raise SalesfoceIntegrationError, "Standard price book not found for #{product_code}"
end

standard_id = standard['Id']
product_id = results.first['Id']

pricebookentry = SFService::Base.new "PricebookEntry", config

pricebook_entry = find_pricebook_entry(standard_id, product_id)

if pricebook_entry && !pricebook_entry["IsActive"]
pricebook_entry_id = pricebook_entry["Id"]
pricebookentry.update!(IsActive: true, Id: pricebook_entry_id)
else
pricebook_entry_id = pricebook_entry["Id"]
end

unless pricebook_entry
pricebook_entry_id = pricebookentry.create!(
Pricebook2Id: standard["Id"],
Product2Id: product_id,
UnitPrice: line_item_attr["UnitPrice"],
IsActive: true
)
end

if line_item_id = find_line_item(order_id, pricebook_entry_id)
line_item_attr = line_item_attr.merge OpportunityId: order_id , PricebookEntryId: pricebook_entry_id
create!(line_item_attr)
else
update!(line_item_attr.merge Id: line_item_id )
end
end
end
end
7 changes: 4 additions & 3 deletions lib/SF_services/product.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,12 @@ def upsert!(product_code, attributes = {})

if product_id.present?
update!(attributes.merge({ Id: product_id }))

result = salesforce.query "select Id from PricebookEntry where Pricebook2Id = '#{standard["Id"]}' and Product2Id = '#{product_id}'"
pricebookentry_id = result.first["Id"]

pricebookentry.update!(Id: pricebookentry_id, UnitPrice: price)
# NOTE Create if can find pricebook entry?
if result.first && pricebookentry_id = result.first["Id"]
pricebookentry.update!(Id: pricebookentry_id, UnitPrice: price)
end
else
product_id = create!(attributes)
pricebookentry.create!(
Expand Down
2 changes: 1 addition & 1 deletion lib/integrations/builders/line_item.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def build
params = {
'Quantity' => object['quantity'],
'UnitPrice' => object['price'],
'CurrencyIsoCode' => object['currency'],
# 'CurrencyIsoCode' => object['currency'],
}
end
end
Expand Down
6 changes: 3 additions & 3 deletions lib/integrations/builders/order.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ def build
'AccountId' => object['email'],
'Amount' => object['totals']['order'],
'CloseDate' => object['placed_on'],
'HasOpportunityLineItem' => true,
# 'HasOpportunityLineItem' => true,
'Name' => object['id'],
'Pricebook2Id' => object['price_book_id'].present? ? object['price_book_id'] : 'standard price list',
'Pricebook2Id' => object['price_book_id'] || 'Standard Price Book',
'StageName' => 'closed-won',
'CurrencyIsoCode' => object['currency']
# 'CurrencyIsoCode' => object['currency']
}
end
end
Expand Down
5 changes: 1 addition & 4 deletions lib/integrations/builders/order_product.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,9 @@ def build
params = {
'Name' => object['name'],
'ProductCode' => object['product_id'],
'Price__c' => object['price'],
'ExternalID__c' => object['product_id'],
'Currency__c' => object['currency'],
'DefaultPrice' => object['price']
}
end

end
end
end
2 changes: 2 additions & 0 deletions lib/salesforce_integration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,5 @@
require 'SF_services/order'
require 'SF_services/line_item'
require 'SF_services/payment'

class SalesfoceIntegrationError < StandardError; end
8 changes: 5 additions & 3 deletions salesforce_endpoint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ class SalesforceEndpoint < EndpointBase::Sinatra::Base
post path do
SpreeService::Order.new(@payload, @config).upsert_contact_with_account!
SpreeService::Order.new(@payload, @config).upsert_order!
SpreeService::Product.new(@payload, @config).upsert_products!

Integration::Product.new(@config, @payload).import_from_order!

SpreeService::Order.new(@payload, @config).upsert_lineitems!
SpreeService::Order.new(@payload, @config).upsert_payments!
set_summary "Contact for #{@payload["order"]["email"]} and order ##{@payload["order"]["id"]} updated (or created) in Salesforce"
result 200

result 200, "Opportunity ##{@payload["order"]["id"]} sent to Salesforce"
end
end

Expand Down
85 changes: 0 additions & 85 deletions spec/cassettes/requests/add_order.yml

This file was deleted.

63 changes: 9 additions & 54 deletions spec/salesforce_endpoint_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,63 +3,18 @@
describe SalesforceEndpoint do
include_examples 'config hash'

context 'webhooks' do
['add_order', 'update_order'].each do |path|
describe path do
let(:payload) do
payload = Factories.send("#{path}_payload")
payload.merge(parameters: config)
end

it 'works' do
VCR.use_cassette "requests/#{path}" do
post "/#{path}", payload.to_json, auth
expect(last_response).to be_ok
body = JSON.parse(last_response.body)
expect(body["request_id"]).to eq payload["request_id"]
end
end
end
context "orders" do
let(:payload) do
payload = Factories.send("add_order_payload")
payload.merge(parameters: config)
end
end

describe "upserting clients with accounts" do
['add_order', 'update_order'].each do |path|
describe path do
let(:payload) do
payload = Factories.send("#{path}_payload")
payload.merge(parameters: config)
end
let(:customer_email){ payload["order"].nil? ? payload["customer"]["email"] : payload["order"]["email"] }

it 'works' do
VCR.use_cassette "requests/#{path}" do
post "/#{path}", payload.to_json, auth
body = JSON.parse(last_response.body)
expect(body["summary"]).to match "Contact for #{customer_email}"
end
end
end
end
end
it "adds" do
VCR.use_cassette "requests/add_order" do
post "/add_order", payload.to_json, auth

describe "upserting orders" do
['add_order', 'update_order'].each do |path|
describe path do
let(:payload) do
payload = Factories.send("#{path}_payload")
payload.merge(parameters: config)
end
let(:customer_email) { payload["order"]["email"] }
let(:order_id){ payload["order"]["id"] }

it 'works' do
VCR.use_cassette "requests/#{path}" do
post "/#{path}", payload.to_json, auth
body = JSON.parse(last_response.body)
expect(body["summary"]).to eq "Contact for #{customer_email} and order ##{order_id} updated (or created) in Salesforce"
end
end
expect(json_response["summary"]).to match "sent to Salesforce"
expect(last_response.status).to eq 200
end
end
end
Expand Down

0 comments on commit 939ceac

Please sign in to comment.