Class: Spree::TaxCloud

Inherits:
Object
  • Object
show all
Defined in:
app/models/spree/tax_cloud.rb

Class Method Summary collapse

Class Method Details

.address_from_spree_address(address) ⇒ Object

Note that this method can take either a Spree::StockLocation (which has address attributes directly on it) or a Spree::Address object



33
34
35
36
37
38
39
40
41
# File 'app/models/spree/tax_cloud.rb', line 33

def self.address_from_spree_address(address)
  ::TaxCloud::Address.new(
    address1: address.address1,
    address2: address.address2,
    city: address.city,
    state: address.try(:state).try(:abbr),
    zip5: address.zipcode.try(:[], 0...5)
  )
end

.cart_item_from_item(item, index) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'app/models/spree/tax_cloud.rb', line 43

def self.cart_item_from_item(item, index)
  case item
  when Spree::LineItem
    ::TaxCloud::CartItem.new(
      index: index,
      item_id: item.try(:variant).try(:sku).presence || "LineItem #{item.id}",
      tic: (item.product.tax_cloud_tic || Spree::Config.taxcloud_default_product_tic),
      price: item.price_with_discounts,
      quantity: item.quantity
    )
  when Spree::Shipment
    ::TaxCloud::CartItem.new(
      index: index,
      item_id: "Shipment #{item.number}",
      tic: Spree::Config.taxcloud_shipping_tic,
      price: item.price_with_discounts,
      quantity: 1
    )
  else
    raise I18n.t('spree.cart_item_cannot_be_made')
  end
end

.transaction_from_order(order) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/models/spree/tax_cloud.rb', line 5

def self.transaction_from_order(order)
  stock_location = order.shipments.first.try(:stock_location) || Spree::StockLocation.active.where('city IS NOT NULL and state_id IS NOT NULL').first
  raise I18n.t('spree.ensure_one_valid_stock_location') unless stock_location

  destination = address_from_spree_address(order.ship_address || order.billing_address)
  begin
    destination = destination.verify # Address validation may fail, and that is okay.
  rescue ::TaxCloud::Errors::ApiError
  end

  transaction = ::TaxCloud::Transaction.new(
    customer_id: order.user_id || order.email,
    order_id: order.number,
    cart_id: order.number,
    origin: address_from_spree_address(stock_location),
    destination: destination
  )

  index = -1 # array is zero-indexed
  # Prepare line_items for lookup
  order.line_items.each { |line_item| transaction.cart_items << cart_item_from_item(line_item, index += 1) }
  # Prepare shipments for lookup
  order.shipments.each { |shipment| transaction.cart_items << cart_item_from_item(shipment, index += 1) }
  transaction
end