Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #This implements the general JS logic for the checkout
- registerFinePrintHandler = (options) ->
- buttonQuerySelector = options.buttonSelector
- textQuerySelector = options.textSelector
- $button = $(buttonQuerySelector)
- $text = $(textQuerySelector)
- $button.click ->
- $text.slideToggle()
- retrieveUserInformation = (select, isAddress, url) ->
- select.on 'change', (e) ->
- e.preventDefault()
- $this = $(this)
- $parent = $this.parent()
- if isAddress
- address_type = $parent.attr("data_address").replace('_','-')
- if isAddress
- form = if address_type == 'address' then $('.delivery-delivery-form') else $("." + address_type)
- else
- form = $('.credit-card-info')
- # Value equal 0 represents the add option
- if $(this).val() != '0'
- form.find(".create").fadeOut()
- form.find(".create input").prop('checked', false)
- $.ajax
- type: 'get'
- url: url + $(this).val()
- dataType: 'json'
- complete: (response) =>
- if response.status == 200
- collection = response.responseJSON
- for key of collection
- form.find("#" + key).val(collection[key])
- if key == 'country_id'
- if address_type == 'address'
- handleUserAddressRender($('#delivery_country'), collection[key], ThisPage.deliveryHandler, $('#order_country_postage_id'), $(".delivery"))
- if address_type == 'return-address'
- handleUserAddressRender($('#order_post_country_id'), collection[key], ThisPage.postHandler, $("#order_country_return_postage_id"), $(".post-return"))
- form.find("#" + key).selectpicker('refresh')
- form.find("#user_card_id").val($this.val())
- form.find(".update").fadeIn()
- else
- # show add checkbox
- form.find(".create").fadeIn()
- form.find(".update").fadeOut()
- form.find(".update input").prop('checked', false)
- handleUserAddressRender = (element, value, handler, country_element, active) ->
- # if country is not available render modal
- if element.find("option[value='#{value}']").length == 0
- handleInvalidAddressModalActions(handler, element, value, country_element, active)
- else
- element.val(value)
- element.selectpicker('refresh')
- handler.inhibitNextOnCountryChanged()
- element.change()
- handleInvalidAddressModalActions = (handler, element, value, country_element, active) ->
- $modal = $("#invalid-address")
- $modal.fadeIn()
- $modal.find("#cancel").on 'click', ->
- country_element.val(value)
- element.val(value)
- element.selectpicker('refresh')
- handler.inhibitNextOnCountryChanged()
- element.change()
- $modal.fadeOut()
- $modal.find("#use").on 'click', ->
- element.selectpicker('refresh')
- country_element.val(element.val())
- country_element.selectpicker('refresh')
- active.find(".cost-and-quantity a.active").click()
- $modal.fadeOut()
- class NewOrderPage
- constructor: (options) ->
- _(this).extend(options) if options
- @currency = Cookies.get 'currency'
- @initOrderView()
- @fixSidebarPosition()
- @lastOrderStateFiller = new LastOrderStateFiller(this)
- @addressManager = new AddressManager(this)
- this
- registerMoreThanTenDevices: (options) ->
- inputQuerySelector = options.inputSelector
- targetUrl = options.targetUrl
- $input = $(inputQuerySelector)
- $input.on 'change', =>
- if parseInt($input.val()) == 11
- @exitOrderPage = true
- window.open(targetUrl,"_self")
- fixSidebarPosition: ->
- fix = -> $('#sidebar').affix("checkPosition")
- $ fix
- setTimeout(fix,0)
- registerCallbacks: ->
- @registerMoreThanTenDevices
- inputSelector: "#order_n_devices"
- targetUrl: "/group_orders/new"
- # @phoneNumberPlaceholderManager = new PhoneNumberPlaceholderManager(this)
- # @phoneNumberPlaceholderManager.registerCallbacks()
- @buildRatingOnFooter()
- @sectionCollapser = new SectionCollapser(this)
- @sectionCollapser.registerCallbacks()
- @orderValidator = new OrderValidator(this)
- @orderValidator.registerCallbacks()
- @initCouponValidator()
- @onlyDisplayCurrentCurrency()
- @registerCurrencyCallbacks()
- @getNumberOfDevicesField().on 'change', @updateOrderView.bind(this)
- @pickupHandler = new PickupDeliveryHandler(this)
- @pickupHandler.registerCallbacks()
- @deliveryHandler = new DeliveryDeliveryHandler(this)
- @deliveryHandler.registerCallbacks()
- @addressCheckAction()
- @registerBillingDetailsCallbacks()
- @formSubmitter = new FormSubmitter(this)
- @formSubmitter.registerCallbacks()
- @checkIfApplePayIsAvailable()
- @registerErrorPageCallbacks()
- @bindPageAlert()
- @loadPurposeUnselect()
- @lastOrderStateFiller.fill()
- buildRatingOnFooter: ->
- ratingValue = $(".rating").attr("data-score")
- $('.rate').rateYo
- rating: ratingValue
- starWidth: '20px'
- spacing: '5px'
- ratedFill: '#ffd200'
- readOnly: true
- normalFill: '#FFFFFF'
- checkIfApplePayIsAvailable: ->
- applePayContainer = $(".apple_pay")
- paymentsContainer = $(".payments > div")
- Stripe.applePay.checkAvailability (available) ->
- if available
- paymentsContainer.removeClass("col-sm-6").addClass("col-sm-4")
- applePayContainer.show()
- return
- return
- addressCheckAction: ->
- addressCheckbox = $("input#use_delivery_as_return_address")
- addressCheckbox.on 'change', ->
- if this.checked
- $('.return-address').fadeOut()
- else
- $('.return-address').fadeIn()
- loadPurposeUnselect: ->
- $('#purpose label').on 'click', (evt)->
- if $(this).prev().is ":checked"
- evt.preventDefault()
- $(this).prev().attr "checked", false
- bindPageAlert: ->
- @exitOrderPage = false
- myEvent = window.attachEvent or window.addEventListener
- chkevent = if window.attachEvent then 'onbeforeunload' else 'beforeunload'
- myEvent chkevent, (e) =>
- if !@exitOrderPage
- # For >=IE7, Chrome, Firefox
- confirmationMessage =
- 'The progress of your order will be lost if you leave this page.'
- (e or window.event).returnValue = confirmationMessage
- confirmationMessage
- return
- showErrorPage: (errorMessage)->
- $('.container.order-error .error-message-description').html(errorMessage)
- $('.container.new-order-form').fadeOut 400, ->
- $('.container.order-error').fadeIn()
- showEmailErrorPage: (errorMessage)->
- $('.container.order-email-error .error-message-description').html(errorMessage)
- $('.container.new-order-form').fadeOut 400, ->
- $('.container.order-email-error').fadeIn()
- hideErrorPage: ->
- $('button#complete-order-button').prop 'disabled', false
- $('button#complete-order-button i').addClass('hidden')
- $('.container.order-error').fadeOut 400, ->
- $('.container.new-order-form').fadeIn()
- registerErrorPageCallbacks: =>
- $(".try-again").click (e)=>
- e.preventDefault()
- @hideErrorPage()
- registerBillingDetailsCallbacks: ->
- addressCheckbox = $("input#use_delivery_address")
- addressCheckbox.on 'change', ->
- if this.checked
- $('.billing-address').fadeOut()
- else
- $('.billing-address').fadeIn()
- $("input[name=payment_type]").on 'change', ->
- $this = $(this)
- if($this.val() == 'paypal')
- $('.credit-card-info').fadeOut()
- $('#billing-address-section .name-and-email').fadeOut()
- $('#paypal-note').removeClass("hidden")
- $('#paypal-note').hide()
- $('#paypal-note').fadeIn()
- else if($this.val() == 'apple_pay')
- $('.credit-card-info').fadeOut()
- $('#billing-address-section .name-and-email').fadeIn()
- $('#paypal-note').fadeOut()
- else
- $('.credit-card-info').fadeIn()
- $('#billing-address-section .name-and-email').fadeIn()
- $('#paypal-note').fadeOut()
- getNumberOfDevices: ->
- parseInt @getNumberOfDevicesField().val()
- getNumberOfDevicesField: -> $("#order_n_devices")
- updateOrderView: -> @orderView.update()
- registerCurrencyCallbacks: ->
- CurrencySelector.onChange (currency)=>
- @currency = currency
- @onlyDisplayCurrentCurrency()
- onlyDisplayCurrentCurrency: ->
- Amount.onlyDisplay(@currency)
- initializeAddOnModelActions: ->
- $('.add-on').click ->
- sku = $(this).attr('data-sku')
- $('ul').find('.modal[data-sku=\'' + sku + '\']').fadeIn()
- return
- $(".close").click ->
- $(".modal").fadeOut()
- onAddToCartPressed: (event) ->
- event.preventDefault()
- has_date = $("#order_start_date").val() != "" && $("#order_end_date").val() != ""
- button = $ event.target
- extraDiv = button.parents '.extra'
- id = extraDiv.find(".extra_id").val()
- extra = @getExtraWithId parseInt(id)
- quantity = parseInt(extraDiv.find("select.extra_quantity").val())
- if (extra.daily && has_date) || !(button.hasClass("active") || quantity == 0) && !extra.daily
- $(".date-error").fadeOut()
- button.html "ADDED TO CART"
- button.addClass 'active'
- extraDiv.find(".form-title").addClass("hidden")
- extraDiv.find(".brief-title").removeClass("hidden")
- extraDiv.find('.on_cart').val(true)
- if quantity != 0
- @addToCart
- extra: extra
- quantity: quantity
- if quantity == 0
- @resetAddToCartButton(extraDiv)
- else
- extraDiv.find("select.extra_quantity").val('0').change()
- $(".date-error").fadeIn() if extra.daily
- return false
- onAddOnAddCartPressed: (event) ->
- event.preventDefault()
- button = $(event.target);
- add_on_modal = button.parents '.modal'
- id = add_on_modal.attr("data-id")
- add_on = @getAddOnWithId parseInt(id)
- addOnDiv = $(".add-on[data-sku='" + add_on.sku + "']")
- onCart = addOnDiv.find('.on_cart')
- if onCart.val() == "false"
- button.html "REMOVE FROM CART"
- addOnDiv.addClass 'active'
- onCart.val(true)
- @addToCartAddOn
- add_on: add_on
- quantity: 1
- else
- button.html "ADD TO CART"
- addOnDiv.removeClass 'active'
- @orderView.removeAddOn(id)
- onCart.val(false)
- resetAddToCartButton: (extraDiv)->
- button = extraDiv.find('.add-to-cart .btn')
- extraDiv.find('.on_cart').val(false)
- button.html "ADD TO CART"
- button.removeClass 'active'
- extraDiv.find(".form-title").removeClass("hidden")
- extraDiv.find(".brief-title").addClass("hidden")
- getExtraWithId:(id) ->
- vals = @getExtras().filter (e)->
- e.id == id
- if vals.length > 0 then vals[0] else null
- getAddOnWithId: (id) ->
- vals = @getAddOns().filter (a) ->
- a.id == id
- if vals.length > 0 then vals[0] else null
- addToCart: (options) ->
- extra = options.extra
- quantity = options.quantity
- @orderView.addExtra options
- addToCartAddOn: (options) ->
- add_on = options.add_on
- quantity = 1
- @orderView.addAddOn options
- registerExtrasCallbacks: ->
- $('.extras .add-to-cart .btn').click (clickEvent) =>
- @onAddToCartPressed(clickEvent)
- $('.extras .extra_quantity').change (event)=>
- $target = $(event.target)
- extraDiv = $target.parents('.extra')
- id = extraDiv.find(".extra_id").val()
- extra = @getExtraWithId parseInt(id)
- @orderView.removeExtra(id)
- @resetAddToCartButton extraDiv
- registerAddOnCallbacks: ->
- $('.modal .modal-header .btn').click (clickEvent) =>
- clickEvent.preventDefault()
- @onAddOnAddCartPressed(clickEvent)
- getDailyPriceString: ->
- value = @destination.prices[@currency]
- priceString =
- eur: "#{value}€"
- pound: "#{value}£"
- dollar: "$#{value}"
- priceString[@currency]
- getNumberOfDays: () ->
- startDateStr = $('#order_start_date').val()
- endDateStr = $('#order_end_date').val()
- updatePriceBox: ->
- AmountView.update
- el: '.unlimited-internet-ad .price .currency-amount'
- eur: @destination.prices['eur']
- usd: @destination.prices['usd']
- gbp: @destination.prices['gbp']
- class FormSubmitter
- constructor: (@page) ->
- getPaymentType: ->
- $('input[name=payment_type]:checked').val() || "stripe"
- stripeResponseHandler: (status, response) ->
- $form = $('form')
- if response.error
- console.log JSON.stringify(response)
- element = null
- param = response.error.param.replace('_', '-')
- if param == ''
- param = 'number'
- if param == 'exp-month' or param == 'exp-year'
- element = $('select[data-stripe=' + param + ']').parent()
- else
- element = $('input[data-stripe=' + param + ']')
- ThisPage.orderValidator.showError
- message: response.error.message
- element: element
- # Show the errors on the form
- #$form.find('.payment-errors').text response.error.message
- $form.find('#complete-order-button').prop 'disabled', false
- $form.find('button#complete-order-button i').addClass('hidden')
- else
- # response contains id and card, which contains additional card details
- token = response.id
- # Insert the token into the form so it gets submitted to the server
- $form.append $('<input type="hidden" name="stripeToken" />').val(token)
- # and submit
- $ @submit.bind(this)
- createApplePayOrder: ->
- # Ajax call to create the order, this have to be sync because we need the order info to create a new apple pay session
- paymentRequest = {}
- requestObject = {}
- $ =>
- data = $('form').serialize()
- $.ajax
- type: 'post'
- data: data
- async: false
- dataType: 'json'
- url: @page.basePath
- success: (response) =>
- country_code = $(".apple_pay").attr("data_country")
- paymentRequest = {
- countryCode: country_code,
- currencyCode: response.currency.toUpperCase(),
- total: {
- label: 'for tepwireless',
- amount: response.original_price
- }
- }
- requestObject = {orderid: response.id,payment:paymentRequest}
- error: (error) =>
- console.log(error)
- return requestObject
- buildApplePaySession: (paymentObject,currThis) ->
- session = Stripe.applePay.buildSession(paymentObject.payment, ((result, completion) ->
- payment_url = currThis.page.basePath + "/payment_apple_pay"
- success_url = currThis.page.basePath + "/order_success"
- $.post(payment_url, token: result.token.id,id:paymentObject.orderid).done(->
- completion ApplePaySession.STATUS_SUCCESS
- $.get(success_url,apple_order_id:paymentObject.orderid).done(->
- window.location = success_url + "?apple_order_id=" + paymentObject.orderid
- ).fail((jqXHR,textStatus) ->
- if jqXHR.status == 503
- order_id = JSON.parse(jqXHR.responseText).order_id
- currThis.page.showEmailErrorPage("Your order number " + order_id + " has been processed but the confirmation email was not successfully sent.")
- else
- currThis.page.showErrorPage("")
- return
- )
- ).fail ->
- completion ApplePaySession.STATUS_FAILURE
- currThis.page.showErrorPage("")
- return
- return
- ), (error) ->
- currThis.page.showErrorPage("")
- return
- )
- return session
- submit: ->
- fbq('track', 'InitiateCheckout')
- if @getPaymentType() == 'stripe'
- cc=$('input[data-stripe="number"]').val()
- lastDigits = cc.substring(cc.length - 4, cc.length)
- $('#order_cc_end').val(lastDigits)
- $ =>
- data = $('form.new_order').serialize()
- $.ajax
- type: 'post'
- url: @page.basePath
- data: data
- dataType: 'json'
- success: (response) =>
- @page.exitOrderPage = true
- paymentMethod = @getPaymentType()
- url =
- if paymentMethod == 'stripe'
- "#{@page.basePath}/order_success"
- else
- "#{@page.basePath}/payment"
- form = $("<form action='#{url}' method='post'>\
- <input type='text' name='id' value=#{response.id} />\
- </form>")
- $('body').append(form)
- form.submit()
- error: (response) =>
- if response.status == 422
- @page.orderValidator.handleValidationResponse(response)
- else if response.status == 401
- @page.showErrorPage(response.responseJSON.error_message)
- else if response.status == 503
- order_id = JSON.parse(response.responseText).order_id
- @page.showEmailErrorPage("Your order number " + order_id + " has been processed but the confirmation email was not successfully sent.")
- else
- @page.showErrorPage("")
- validateUserAccount: ($form, paymentType, applePaySession) ->
- data = $form.serialize()
- $.ajax
- type: 'post'
- url: '/front_users/'
- data: data
- dataType: 'json'
- success: (response) =>
- $form.find('.error-message').remove()
- $form.find('input#front_users_id').val(response.id)
- @handleFormSubmit($form, paymentType, applePaySession)
- error: (errors) =>
- errorsObject = if errors.responseJSON != undefined then errors.responseJSON.errors else []
- for key of errorsObject
- $form.find("#front_user_#{key}").parent().append("<span class='error-message'>#{errorsObject[key]}</span>")
- $form.find('#complete-order-button').prop 'disabled', false
- $form.find('button#complete-order-button i').addClass('hidden')
- $form.find('.complete-order .button-container').parent().append("<span class='error-message'>PLEASE REVIEW THE FIELDS ABOVE</span>")
- handleFormSubmit: ($form, paymentType, applePaySession) ->
- @page.orderValidator.trackCheckoutFunnel 4, =>
- isSuccess = true
- if paymentType == 'stripe'
- if $("#use_customer").val() == 'true'
- $ @submit.bind(this)
- else
- Stripe.card.createToken $form, @stripeResponseHandler.bind(this)
- return false
- else if paymentType == 'apple_pay'
- $form.find('#complete-order-button').prop 'disabled', false
- $form.find('button#complete-order-button i').addClass('hidden')
- applePaySession.begin()
- return false
- else
- @submit()
- registerCallbacks: ->
- $form = $ 'form.new_order'
- $form.on 'submit', (event) =>
- event.preventDefault()
- paymentType = @getPaymentType()
- if paymentType == 'apple_pay'
- applePaymentObject = @createApplePayOrder()
- applePaySession = @buildApplePaySession(applePaymentObject,this)
- # Disable the submit button to prevent repeated clicks
- $form.find('#complete-order-button').prop 'disabled', true
- $form.find('button#complete-order-button i').removeClass('hidden')
- completeOrderBtn = $form.find('#complete-order-button')
- @page.orderValidator.lastPressedContinueButton = completeOrderBtn
- @page.orderValidator.hideErrors()
- @page.orderValidator.validateThirdSection
- success: =>
- if $(".create-account #create_account").prop("checked")
- password = $(".create-account #front_user_password").val()
- $(".create-account #front_user_password_confirmation").val(password)
- @validateUserAccount($form, paymentType, applePaySession)
- else
- @handleFormSubmit($form, paymentType, applePaySession)
- # Prevent the form from submitting with the default action
- error: ->
- $form.find('#complete-order-button').prop 'disabled', false
- $form.find('button#complete-order-button i').addClass('hidden')
- return false
- class SectionCollapser
- constructor: (@page)->
- registerCallbacks: ->
- return
- toggleTargetSection: (event) ->
- section = $(event.target).parents("section")
- collapserIcon = section.find('.collapser i')
- collapsable = section.find('.collapsable')
- if collapserIcon.hasClass('fa-chevron-up')
- collapserIcon.removeClass('fa-chevron-up')
- collapserIcon.addClass('fa-chevron-down')
- collapsable.fadeOut => @page.fixSidebarPosition()
- else
- collapserIcon.removeClass('fa-chevron-down')
- collapserIcon.addClass('fa-chevron-up')
- collapsable.fadeIn => @page.fixSidebarPosition()
- uncollapseDeliveryDetails: ->
- section = $('section.delivery')
- collapserIcon = section.find('.collapser i')
- collapsable = section.find('.collapsable')
- collapserIcon.removeClass('fa-chevron-down')
- collapserIcon.addClass('fa-chevron-up')
- collapsable.fadeIn => @page.fixSidebarPosition()
- uncollapseAddOnsDetails: ->
- section = $('section.add-ons')
- collapserIcon = section.find('.collapser i')
- collapsable = section.find('.collapsable')
- collapserIcon.removeClass('fa-chevron-down')
- collapserIcon.addClass('fa-chevron-up')
- collapsable.fadeIn => @page.fixSidebarPosition()
- uncollapseBillingDetails: ->
- section = $('section.billing')
- collapserIcon = section.find('.collapser i')
- collapsable = section.find('.collapsable')
- collapserIcon.removeClass('fa-chevron-down')
- collapserIcon.addClass('fa-chevron-up')
- collapsable.fadeIn => @page.fixSidebarPosition()
- class Extra
- constructor: (options) ->
- _(this).extend options
- class AddOn
- constructor: (options) ->
- _(this).extend options
- class AddressManager
- constructor: (options) ->
- _(this).extend options
- isDefaultDeliverySelected: ->
- $('.delivery-delivery-form[data-address-is-default]').length > 0
- isDefaultReturnSelected: ->
- $('.return-address[data-address-is-default]').length > 0
- resetDeliveryAddress: ->
- @resetAddressForm $('.delivery-delivery-form')
- resetReturnAddress: ->
- @resetAddressForm $('.return-address')
- resetAddressForm: (topLevelElement) ->
- addressSelector = topLevelElement.find '.user-select'
- topLevelElement.find('input[type=text]').val('')
- addressSelector.val(0)
- addressSelector.selectpicker("refresh")
- addressSelector.trigger('change')
- root = exports ? this
- root.NewOrderPage = NewOrderPage
- root.Extra = Extra
- root.AddressManager = AddressManager
- root.AddOn = AddOn
- $ ->
- if $("body.orders, body.sales").length > 0
- $("section.delivery .sign-in a").bind 'click', ->
- $(".sign-modal").fadeIn()
- return
- use_customer = $(".credit-card-info #use_customer")
- $(".credit-card-info input").on 'change', ->
- if use_customer.val() == 'true'
- use_customer.val('false')
- $(".create-account #create_account").click (e) ->
- $this = $(this)
- if $this.prop("checked")
- $this.parent().find(".fields").fadeIn()
- email = if $(".delivery-delivery-form #email").val() != '' then $(".delivery-delivery-form #email").val() else $(".billing-address #email").val()
- $(".create-account #front_user_email").val(email)
- else
- $this.parent().find(".fields").fadeOut()
- retrieveUserInformation($(".user-addresses select"), true, '/front_users/addresses/')
- retrieveUserInformation($(".user-payments select"), false, '/front_users/payments/')
- $(".new_front_user .submit").click (e) ->
- ThisPage.exitOrderPage = true
- $.ajax
- type: 'post'
- data: $("#new_order").serialize()
- url: ThisPage.basePath + '/save_order_state'
- success: (response) =>
- error: (response) =>
- $('[data-toggle="popover"]').popover
- trigger: 'hover'
- if(".order_success").length > 0
- ratingValue = $(".rating").attr("data-score")
- $('.rate').rateYo
- rating: ratingValue
- starWidth: '20px'
- spacing: '5px'
- ratedFill: '#ffd200'
- readOnly: true
- normalFill: '#FFFFFF'
- registerFinePrintHandler
- buttonSelector: '.unlimited-internet-ad'
- textSelector: '.unlimited-instructions'
- # Address and Billing address phone country code
- $('''#order_address_attributes_country_code,
- #order_billing_address_attributes_country_code''').selectpicker
- showSubtext: true
- showContent: true
- mobile: true
- dropupAuto: false
- prefix = $('#order_address_attributes_country_code').data('phone-prefix')
- $('#order_address_attributes_country_code').selectpicker('val', prefix)
- $('#order_billing_address_attributes_country_code')
- .selectpicker('val',
- $('#order_billing_address_attributes_country_code')
- .data('phone-prefix'))
- if $("body.orders, body.errors").length == 0
- $('.navbar select.destinations').selectpicker()
- $('.navbar .btn-group.destinations').addClass('bounceInDown')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement