require 'spec_helper'

describe Sale do

  let(:user) {FactoryGirl.create(:user)}
  let(:user2) {FactoryGirl.create(:user)}
  let(:jam_track) {FactoryGirl.create(:jam_track)}

  describe "index" do
    it "empty" do
      result = Sale.index(user)
      result[:query].length.should eq(0)
      result[:next].should eq(nil)
    end

    it "one" do
      sale = Sale.create_jam_track_sale(user)
      shopping_cart = ShoppingCart.create(user, jam_track)
      sale_line_item = SaleLineItem.create_from_shopping_cart(sale, shopping_cart, nil, 'some_adjustment_uuid', nil)

      result = Sale.index(user)
      result[:query].length.should eq(1)
      result[:next].should eq(nil)
    end

    it "user filtered correctly" do
      sale = Sale.create_jam_track_sale(user)
      shopping_cart = ShoppingCart.create(user, jam_track)
      sale_line_item = SaleLineItem.create_from_shopping_cart(sale, shopping_cart, nil, 'some_adjustment_uuid', nil)

      result = Sale.index(user)
      result[:query].length.should eq(1)
      result[:next].should eq(nil)

      sale2 = Sale.create_jam_track_sale(user2)
      shopping_cart = ShoppingCart.create(user2, jam_track)
      sale_line_item2 = SaleLineItem.create_from_shopping_cart(sale2, shopping_cart, nil, 'some_adjustment_uuid', nil)

      result = Sale.index(user)
      result[:query].length.should eq(1)
      result[:next].should eq(nil)
    end
  end


  describe "place_order" do

    let(:user) {FactoryGirl.create(:user)}
    let(:jamtrack) { FactoryGirl.create(:jam_track) }
    let(:jam_track_price_in_cents) { (jamtrack.price * 100).to_i }
    let(:client) { RecurlyClient.new }
    let(:billing_info) {
      info = {}
      info[:first_name] = user.first_name
      info[:last_name] = user.last_name
      info[:address1] = 'Test Address 1'
      info[:address2] = 'Test Address 2'
      info[:city] = user.city
      info[:state] = user.state
      info[:country] = user.country
      info[:zip] = '12345'
      info[:number] = '4111-1111-1111-1111'
      info[:month] = '08'
      info[:year] = '2017'
      info[:verification_value] = '111'
      info
    }

    after(:each) do
      if user.recurly_code
        account = Recurly::Account.find(user.recurly_code)
        if account.present?
          account.destroy
        end
      end
    end


    it "for a free jam track" do
      shopping_cart = ShoppingCart.create user, jamtrack, 1, true
      client.find_or_create_account(user, billing_info)

      sales = Sale.place_order(user, [shopping_cart])

      user.reload
      user.sales.length.should eq(1)

      sales.should eq(user.sales)
      sale = sales[0]
      sale.recurly_invoice_id.should be_nil

      sale.recurly_subtotal_in_cents.should eq(0)
      sale.recurly_tax_in_cents.should eq(0)
      sale.recurly_total_in_cents.should eq(0)
      sale.recurly_currency.should eq('USD')
      sale.order_total.should eq(0)
      sale.sale_line_items.length.should == 1
      sale_line_item = sale.sale_line_items[0]
      sale_line_item.recurly_tax_in_cents.should eq(0)
      sale_line_item.recurly_total_in_cents.should eq(0)
      sale_line_item.recurly_currency.should eq('USD')
      sale_line_item.recurly_discount_in_cents.should eq(0)
      sale_line_item.product_type.should eq(JamTrack::PRODUCT_TYPE)
      sale_line_item.unit_price.should eq(jamtrack.price)
      sale_line_item.quantity.should eq(1)
      sale_line_item.free.should eq(1)
      sale_line_item.sales_tax.should be_nil
      sale_line_item.shipping_handling.should eq(0)
      sale_line_item.recurly_plan_code.should eq(jamtrack.plan_code)
      sale_line_item.product_id.should eq(jamtrack.id)
      sale_line_item.recurly_subscription_uuid.should be_nil
      sale_line_item.recurly_adjustment_uuid.should be_nil
      sale_line_item.recurly_adjustment_credit_uuid.should be_nil
      sale_line_item.recurly_adjustment_uuid.should eq(user.jam_track_rights.last.recurly_adjustment_uuid)
      sale_line_item.recurly_adjustment_credit_uuid.should eq(user.jam_track_rights.last.recurly_adjustment_credit_uuid)

      # verify subscription is in Recurly
      recurly_account = client.get_account(user)
      adjustments = recurly_account.adjustments
      adjustments.should_not be_nil
      adjustments.should have(0).items

      invoices = recurly_account.invoices
      invoices.should have(0).items


      # verify jam_track_rights data
      user.jam_track_rights.should_not be_nil
      user.jam_track_rights.should have(1).items
      user.jam_track_rights.last.jam_track.id.should eq(jamtrack.id)
      user.jam_track_rights.last.redeemed.should be_true
      user.has_redeemable_jamtrack.should be_false
    end

    it "for a free jam track with an affiliate association" do
      partner = FactoryGirl.create(:affiliate_partner)
      user.affiliate_referral = partner
      user.save!

      shopping_cart = ShoppingCart.create user, jamtrack, 1, true
      client.find_or_create_account(user, billing_info)

      sales = Sale.place_order(user, [shopping_cart])

      user.reload
      user.sales.length.should eq(1)

      sales.should eq(user.sales)
      sale = sales[0]
      sale.recurly_invoice_id.should be_nil

      sale.recurly_subtotal_in_cents.should eq(0)
      sale.recurly_tax_in_cents.should eq(0)
      sale.recurly_total_in_cents.should eq(0)
      sale.recurly_currency.should eq('USD')
      sale.order_total.should eq(0)
      sale.sale_line_items.length.should == 1
      sale_line_item = sale.sale_line_items[0]
      sale_line_item.recurly_tax_in_cents.should eq(0)
      sale_line_item.recurly_total_in_cents.should eq(0)
      sale_line_item.recurly_currency.should eq('USD')
      sale_line_item.recurly_discount_in_cents.should eq(0)
      sale_line_item.product_type.should eq(JamTrack::PRODUCT_TYPE)
      sale_line_item.unit_price.should eq(jamtrack.price)
      sale_line_item.quantity.should eq(1)
      sale_line_item.free.should eq(1)
      sale_line_item.sales_tax.should be_nil
      sale_line_item.shipping_handling.should eq(0)
      sale_line_item.recurly_plan_code.should eq(jamtrack.plan_code)
      sale_line_item.product_id.should eq(jamtrack.id)
      sale_line_item.recurly_subscription_uuid.should be_nil
      sale_line_item.recurly_adjustment_uuid.should be_nil
      sale_line_item.recurly_adjustment_credit_uuid.should be_nil
      sale_line_item.recurly_adjustment_uuid.should eq(user.jam_track_rights.last.recurly_adjustment_uuid)
      sale_line_item.recurly_adjustment_credit_uuid.should eq(user.jam_track_rights.last.recurly_adjustment_credit_uuid)
      sale_line_item.affiliate_referral.should eq(partner)
      sale_line_item.affiliate_referral_fee_in_cents.should eq(0)

      # verify subscription is in Recurly
      recurly_account = client.get_account(user)
      adjustments = recurly_account.adjustments
      adjustments.should_not be_nil
      adjustments.should have(0).items

      invoices = recurly_account.invoices
      invoices.should have(0).items


      # verify jam_track_rights data
      user.jam_track_rights.should_not be_nil
      user.jam_track_rights.should have(1).items
      user.jam_track_rights.last.jam_track.id.should eq(jamtrack.id)
      user.jam_track_rights.last.redeemed.should be_true
      user.has_redeemable_jamtrack.should be_false
    end


    it "for a normally priced jam track" do
      user.has_redeemable_jamtrack = false
      user.save!
      shopping_cart = ShoppingCart.create user, jamtrack, 1, false
      client.find_or_create_account(user, billing_info)

      sales = Sale.place_order(user, [shopping_cart])

      user.reload
      user.sales.length.should eq(1)

      sales.should eq(user.sales)
      sale = sales[0]
      sale.recurly_invoice_id.should_not be_nil

      sale.recurly_subtotal_in_cents.should eq(jam_track_price_in_cents)
      sale.recurly_tax_in_cents.should eq(0)
      sale.recurly_total_in_cents.should eq(jam_track_price_in_cents)
      sale.recurly_currency.should eq('USD')

      sale.order_total.should eq(jamtrack.price)
      sale.sale_line_items.length.should == 1
      sale_line_item = sale.sale_line_items[0]
      # validate we are storing pricing info from recurly
      sale_line_item.recurly_tax_in_cents.should eq(0)
      sale_line_item.recurly_total_in_cents.should eq(jam_track_price_in_cents)
      sale_line_item.recurly_currency.should eq('USD')
      sale_line_item.recurly_discount_in_cents.should eq(0)
      sale_line_item.product_type.should eq(JamTrack::PRODUCT_TYPE)
      sale_line_item.unit_price.should eq(jamtrack.price)
      sale_line_item.quantity.should eq(1)
      sale_line_item.free.should eq(0)
      sale_line_item.sales_tax.should be_nil
      sale_line_item.shipping_handling.should eq(0)
      sale_line_item.recurly_plan_code.should eq(jamtrack.plan_code)
      sale_line_item.product_id.should eq(jamtrack.id)
      sale_line_item.recurly_subscription_uuid.should be_nil
      sale_line_item.recurly_adjustment_uuid.should_not be_nil
      sale_line_item.recurly_adjustment_credit_uuid.should be_nil
      sale_line_item.recurly_adjustment_uuid.should eq(user.jam_track_rights.last.recurly_adjustment_uuid)

      # verify subscription is in Recurly
      recurly_account = client.get_account(user)
      adjustments = recurly_account.adjustments
      adjustments.should_not be_nil
      adjustments.should have(1).items
      purchase= adjustments[0]
      purchase.unit_amount_in_cents.should eq((jamtrack.price * 100).to_i)
      purchase.accounting_code.should eq(ShoppingCart::PURCHASE_NORMAL)
      purchase.description.should eq("JamTrack: " + jamtrack.name)
      purchase.state.should eq('invoiced')
      purchase.uuid.should eq(sale_line_item.recurly_adjustment_uuid)

      invoices = recurly_account.invoices
      invoices.should have(1).items
      invoice = invoices[0]
      invoice.uuid.should eq(sale.recurly_invoice_id)
      invoice.line_items.should have(1).items # should have single adjustment associated
      invoice.line_items[0].should eq(purchase)
      invoice.subtotal_in_cents.should eq((jamtrack.price * 100).to_i)
      invoice.total_in_cents.should eq((jamtrack.price * 100).to_i)
      invoice.state.should eq('collected')

      # verify jam_track_rights data
      user.jam_track_rights.should_not be_nil
      user.jam_track_rights.should have(1).items
      user.jam_track_rights.last.jam_track.id.should eq(jamtrack.id)
      user.jam_track_rights.last.redeemed.should be_false
      user.has_redeemable_jamtrack.should be_false

      sale_line_item.affiliate_referral.should be_nil
      sale_line_item.affiliate_referral_fee_in_cents.should be_nil
    end


    it "for a normally priced jam track with an affiliate association" do
      user.has_redeemable_jamtrack = false
      partner = FactoryGirl.create(:affiliate_partner)
      user.affiliate_referral = partner
      user.save!
      shopping_cart = ShoppingCart.create user, jamtrack, 1, false
      client.find_or_create_account(user, billing_info)

      sales = Sale.place_order(user, [shopping_cart])

      user.reload
      user.sales.length.should eq(1)

      sales.should eq(user.sales)
      sale = sales[0]
      sale.recurly_invoice_id.should_not be_nil

      sale.recurly_subtotal_in_cents.should eq(jam_track_price_in_cents)
      sale.recurly_tax_in_cents.should eq(0)
      sale.recurly_total_in_cents.should eq(jam_track_price_in_cents)
      sale.recurly_currency.should eq('USD')

      sale.order_total.should eq(jamtrack.price)
      sale.sale_line_items.length.should == 1
      sale_line_item = sale.sale_line_items[0]
      # validate we are storing pricing info from recurly
      sale_line_item.recurly_tax_in_cents.should eq(0)
      sale_line_item.recurly_total_in_cents.should eq(jam_track_price_in_cents)
      sale_line_item.recurly_currency.should eq('USD')
      sale_line_item.recurly_discount_in_cents.should eq(0)
      sale_line_item.product_type.should eq(JamTrack::PRODUCT_TYPE)
      sale_line_item.unit_price.should eq(jamtrack.price)
      sale_line_item.quantity.should eq(1)
      sale_line_item.free.should eq(0)
      sale_line_item.sales_tax.should be_nil
      sale_line_item.shipping_handling.should eq(0)
      sale_line_item.recurly_plan_code.should eq(jamtrack.plan_code)
      sale_line_item.product_id.should eq(jamtrack.id)
      sale_line_item.recurly_subscription_uuid.should be_nil
      sale_line_item.recurly_adjustment_uuid.should_not be_nil
      sale_line_item.recurly_adjustment_credit_uuid.should be_nil
      sale_line_item.recurly_adjustment_uuid.should eq(user.jam_track_rights.last.recurly_adjustment_uuid)
      sale_line_item.affiliate_referral.should eq(partner)
      sale_line_item.affiliate_referral_fee_in_cents.should eq(20)

      # verify subscription is in Recurly
      recurly_account = client.get_account(user)
      adjustments = recurly_account.adjustments
      adjustments.should_not be_nil
      adjustments.should have(1).items
      purchase= adjustments[0]
      purchase.unit_amount_in_cents.should eq((jamtrack.price * 100).to_i)
      purchase.accounting_code.should eq(ShoppingCart::PURCHASE_NORMAL)
      purchase.description.should eq("JamTrack: " + jamtrack.name)
      purchase.state.should eq('invoiced')
      purchase.uuid.should eq(sale_line_item.recurly_adjustment_uuid)

      invoices = recurly_account.invoices
      invoices.should have(1).items
      invoice = invoices[0]
      invoice.uuid.should eq(sale.recurly_invoice_id)
      invoice.line_items.should have(1).items # should have single adjustment associated
      invoice.line_items[0].should eq(purchase)
      invoice.subtotal_in_cents.should eq((jamtrack.price * 100).to_i)
      invoice.total_in_cents.should eq((jamtrack.price * 100).to_i)
      invoice.state.should eq('collected')

      # verify jam_track_rights data
      user.jam_track_rights.should_not be_nil
      user.jam_track_rights.should have(1).items
      user.jam_track_rights.last.jam_track.id.should eq(jamtrack.id)
      user.jam_track_rights.last.redeemed.should be_false
      user.has_redeemable_jamtrack.should be_false
    end

    it "for a jamtrack already owned" do
      shopping_cart = ShoppingCart.create user, jamtrack, 1, true
      client.find_or_create_account(user, billing_info)

      sales = Sale.place_order(user, [shopping_cart])

      user.reload
      user.sales.length.should eq(1)

      shopping_cart = ShoppingCart.create user, jamtrack, 1, false
      sales = Sale.place_order(user, [shopping_cart])
      sales.should have(0).items
      # also, verify that no earlier adjustments were affected
      recurly_account = client.get_account(user)
      adjustments = recurly_account.adjustments
      adjustments.should have(0).items # because the only successful purchase was a freebie, there should be no recurly adjustments
    end

    # this test counts on the fact that two adjustments are made when buying a free JamTrack
    # so if we make the second adjustment invalid from Recurly's standpoint, then
    # we can see if the first one is ultimately destroyed
    it "rolls back created adjustments if error" do

      shopping_cart = ShoppingCart.create user, jamtrack, 1, false

      # grab the real response; we will modify it to make a nil accounting code
      adjustment_attrs = shopping_cart.create_adjustment_attributes(user)
      client.find_or_create_account(user, billing_info)

      adjustment_attrs[0][:unit_amount_in_cents] = nil # invalid amount
      ShoppingCart.any_instance.stub(:create_adjustment_attributes).and_return(adjustment_attrs)

      expect { Sale.place_order(user, [shopping_cart]) }.to raise_error(JamRuby::RecurlyClientError)

      user.reload
      user.sales.should have(0).items

      recurly_account = client.get_account(user)
      recurly_account.adjustments.should have(0).items
    end

    it "rolls back adjustments created before the order" do
      shopping_cart = ShoppingCart.create user, jamtrack, 1, false
      client.find_or_create_account(user, billing_info)

      # create a single adjustment on the account
      adjustment_attrs = shopping_cart.create_adjustment_attributes(user)
      recurly_account = client.get_account(user)
      adjustment = recurly_account.adjustments.new (adjustment_attrs[0])
      adjustment.save
      adjustment.errors.any?.should be_false

      sales = Sale.place_order(user, [shopping_cart])

      user.reload

      recurly_account = client.get_account(user)
      adjustments = recurly_account.adjustments
      adjustments.should have(1).items # two adjustments are created for a free jamtrack; that should be all there is
    end
  end

  describe "check_integrity_of_jam_track_sales" do

    let(:user) { FactoryGirl.create(:user) }
    let(:jam_track) { FactoryGirl.create(:jam_track) }

    it "empty" do
      check_integrity = Sale.check_integrity_of_jam_track_sales
      check_integrity.length.should eq(1)
      r = check_integrity[0]
      r.total.to_i.should eq(0)
      r.voided.to_i.should eq(0)
    end

    it "one succeeded sale" do
      sale = Sale.create_jam_track_sale(user)
      shopping_cart = ShoppingCart.create(user, jam_track)
      SaleLineItem.create_from_shopping_cart(sale, shopping_cart, nil, 'some_recurly_invoice_id', nil)

      check_integrity = Sale.check_integrity_of_jam_track_sales
      r = check_integrity[0]
      r.total.to_i.should eq(1)
      r.voided.to_i.should eq(0)
    end


    it "one voided sale" do
      sale = Sale.create_jam_track_sale(user)
      sale.recurly_invoice_id = 'some_recurly_invoice_id'
      sale.save!
      shopping_cart = ShoppingCart.create(user, jam_track)
      SaleLineItem.create_from_shopping_cart(sale, shopping_cart, nil, 'some_recurly_invoice_id', nil)
      FactoryGirl.create(:recurly_transaction_web_hook, transaction_type: RecurlyTransactionWebHook::VOID, invoice_id: 'some_recurly_invoice_id')

      check_integrity = Sale.check_integrity_of_jam_track_sales
      r = check_integrity[0]
      r.total.to_i.should eq(1)
      r.voided.to_i.should eq(1)
    end

  end
end

