Class: Effective::QbReceipt

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/effective/qb_receipt.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.create_from_order!(order) ⇒ Object

Create a QbReceipt from an Effective::Order



44
45
46
47
# File 'app/models/effective/qb_receipt.rb', line 44

def self.create_from_order!(order)
  raise('Expected a purchased Effective::Order') unless order.kind_of?(Effective::Order) && order.purchased?
  Effective::QbReceipt.where(order: order).first_or_create
end

Instance Method Details

#complete!Object



89
90
91
# File 'app/models/effective/qb_receipt.rb', line 89

def complete!
  completed!
end

#error!Object



93
94
95
96
97
98
# File 'app/models/effective/qb_receipt.rb', line 93

def error!
  errored!
  EffectiveLogger.error(result, associated: self) if defined?(EffectiveLogger)

  false
end

#qb_receipt_item(order_item:) ⇒ Object

Find or build



54
55
56
57
# File 'app/models/effective/qb_receipt.rb', line 54

def qb_receipt_item(order_item:)
  qb_receipt_items.find { |item| item.order_item == order_item } ||
  qb_receipt_items.build(order_item: order_item)
end

#skip!Object



84
85
86
87
# File 'app/models/effective/qb_receipt.rb', line 84

def skip!
  assign_attributes(result: 'skipped')
  skipped!
end

#sync!(force: false) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'app/models/effective/qb_receipt.rb', line 59

def sync!(force: false)
  raise('Already created SalesReceipt with QuickBooks Online') if sales_receipt_id.present? && !force
  save!

  api = EffectiveQbOnline.api

  begin
    sales_receipt = Effective::QbSalesReceipt.build_from_receipt!(self, api: api)
    sales_receipt = api.create_sales_receipt(sales_receipt: sales_receipt)

    # Sanity check
    if (expected = api.price_to_amount(order.total)) != sales_receipt.total
      raise("A QuickBooks Online Sales Receipt has been created with an unexpected total. QuickBooks total is #{sales_receipt.total} but we expected #{expected}. Please adjust the Sales Receipt on QuickBooks")
    end

    assign_attributes(result: 'completed successfully', sales_receipt_id: sales_receipt.id)
    complete!
  rescue => e
    result = [e.message, *("(intuit_tid: #{e.intuit_tid})" if e.try(:intuit_tid).present?), e.backtrace.first(15).join("\n\n")].join(' ')
    assign_attributes(result: result)
    error!
  end

end

#to_sObject



49
50
51
# File 'app/models/effective/qb_receipt.rb', line 49

def to_s
  order.to_s
end