Skip to content

Commit

Permalink
Fix the specs for SSF
Browse files Browse the repository at this point in the history
Frontend paths are no longer defined within the Spree::Core routes and
are now coming directly from the main app.

Removed `Spree::` namespaces where they're no longer needed.

Adjusted selectors for the updated HTML.

Some specs have been changed to reduce the usage of `let` and appease
rubocop.

Use vanilla JS instead of relying on `window.Spree` and jQuery, which
are no longer available in SSF.
  • Loading branch information
elia committed Nov 23, 2022
1 parent 138b2d9 commit b598704
Show file tree
Hide file tree
Showing 9 changed files with 249 additions and 171 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
//= require spree/frontend/solidus_paypal_commerce_platform/namespace
//= require spree/frontend/solidus_paypal_commerce_platform/button_actions
//= require spree/frontend/solidus_paypal_commerce_platform/buttons
//= require_self

Object.assign(SolidusPaypalCommercePlatform, {
current_order_id: null,
current_order_token: null,
api_key: null,
})
Original file line number Diff line number Diff line change
@@ -1,3 +1,37 @@
const urlWithParams = (path, data) => {
const url = new URL(path, window.location)

const formKey = (keys) => {
if (keys.length === 0) return ''
if (keys.length === 1) return keys[0]

// Wrap any key beyond the first one in square brackets
return `${keys.shift()}${keys.map((k) => `[${k}]`).join()}`
}

const appendSearchParams = (parentKeys, data) =>
Object.entries(data).forEach(([key, value]) => {

if (typeof value === 'object')
appendSearchParams([...parentKeys, key], value)
else
url.searchParams.append(formKey([...parentKeys, key]), value)
})

appendSearchParams([], data)
return url
}

const authHeader = (options = {}) => {
const apiKey = SolidusPaypalCommercePlatform.api_key
if (options.require && !apiKey) throw new Error("Missing api key")


return {
'Authorization': `Bearer ${apiKey}`,
[document.querySelector('meta[name="csrf-param"]')?.content]: document.querySelector('meta[name="csrf-token"]')?.content,
}
}
SolidusPaypalCommercePlatform.showOverlay = function() {
document.getElementById("paypal_commerce_platform_overlay").style.display = "block";
}
Expand All @@ -12,59 +46,68 @@ SolidusPaypalCommercePlatform.handleError = function(error) {
throw error
}

SolidusPaypalCommercePlatform.sendOrder = function(payment_method_id) {
return Spree.ajax({
url: '/solidus_paypal_commerce_platform/paypal_orders/' + Spree.current_order_id,
method: 'GET',
data: {
payment_method_id: payment_method_id,
order_token: Spree.current_order_token
}
}).then(function(success_response) {
return success_response.table.result.table.id
}, function(failure_response) {
return failure_response.responseJSON.table.error.table
SolidusPaypalCommercePlatform.sendOrder = async function(payment_method_id) {
console.log('SolidusPaypalCommercePlatform.sendOrder')
if (!payment_method_id) throw new Error("payment_method_id is missing!")

const url = urlWithParams(`/solidus_paypal_commerce_platform/paypal_orders/${SolidusPaypalCommercePlatform.current_order_id}`, {
payment_method_id: payment_method_id,
order_token: SolidusPaypalCommercePlatform.current_order_token,
})

const response = await fetch(url, {headers: authHeader()})
const data = await response.json()

if (response.ok) {
return data.table.result.table.id
} else {
return data.table.error.table
}
}

SolidusPaypalCommercePlatform.createAndSendOrder = function(payment_method_id) {
return SolidusPaypalCommercePlatform.createOrder().then(function(){
return SolidusPaypalCommercePlatform.sendOrder(payment_method_id)
})
SolidusPaypalCommercePlatform.createAndSendOrder = async function(payment_method_id) {
await SolidusPaypalCommercePlatform.createOrder()
return await SolidusPaypalCommercePlatform.sendOrder(payment_method_id)
}

SolidusPaypalCommercePlatform.createOrder = function() {
var data = {
order: {
line_items_attributes: [{
variant_id: SolidusPaypalCommercePlatform.getVariantId(),
quantity: SolidusPaypalCommercePlatform.getQuantity()
}]
SolidusPaypalCommercePlatform.createOrder = async function() {
console.log('SolidusPaypalCommercePlatform.createOrder')
const response = await fetch(
"/solidus_paypal_commerce_platform/orders",
{
method: 'POST',
headers: {
...authHeader(),
'Content-Type': 'application/json'
},
body: JSON.stringify({
order: {
line_items_attributes: [{
variant_id: SolidusPaypalCommercePlatform.getVariantId(),
quantity: SolidusPaypalCommercePlatform.getQuantity()
}]
}
}),
}
}
)
const data = await response.json()

return Spree.ajax({
url: "/solidus_paypal_commerce_platform/orders",
method: 'POST',
data: data,
error: function(response) {
message = response.responseJSON
alert('A problem has occurred while creating your order - ' + message);
}
}).then(function(response) {
Spree.current_order_id = response.number
Spree.current_order_token = response.guest_token
});
if (response.ok) {
SolidusPaypalCommercePlatform.current_order_id = data.number
SolidusPaypalCommercePlatform.current_order_token = data.guest_token
} else {
alert('A problem has occurred while creating your order', data)
}
}

SolidusPaypalCommercePlatform.getVariantId = function() {
var variants = document.getElementsByName("variant_id")
var variant_id;
if(variants.length == 1){

if (variants.length == 1){
variant_id = variants[0].value
}else{
var i;
for (i = 0; i < variants.length; i++) {
} else {
for (var i = 0; i < variants.length; i++) {
if (variants[i].checked) {
variant_id = variants[i].value
}
Expand All @@ -82,50 +125,55 @@ SolidusPaypalCommercePlatform.approveOrder = function(data, actions) {
actions.order.get().then(function(response){
SolidusPaypalCommercePlatform.updateAddress(response).then(function() {
SolidusPaypalCommercePlatform.verifyTotal(response.purchase_units[0].amount.value).then(function(){
$("#payments_source_paypal_order_id").val(data.orderID)
$("#payments_source_paypal_email").val(response.payer.email_address)
$("#payments_source_paypal_funding_source").val(SolidusPaypalCommercePlatform.fundingSource)
$("#checkout_form_payment").submit()
document.querySelector("#payments_source_paypal_order_id").value = data.orderID
document.querySelector("#payments_source_paypal_email").value = response.payer.email_address
document.querySelector("#payments_source_paypal_funding_source").value = SolidusPaypalCommercePlatform.fundingSource
document.querySelector("#checkout_form_payment").submit()
})
})
})
}

SolidusPaypalCommercePlatform.shippingChange = function(data, actions) {
Spree.ajax({
url: '/solidus_paypal_commerce_platform/shipping_rates',
method: 'GET',
data: {
order_id: Spree.current_order_id,
order_token: Spree.current_order_token,
address: data.shipping_address
},
error: function(response) {
message = response.responseJSON;
console.log('There were some problems with your payment address - ' + message);
actions.reject()
}
}).then(function(response) {
actions.order.patch([response]).catch(function() {
SolidusPaypalCommercePlatform.shippingChange = async function(paypalData, actions) {
const shipping_address = paypalData.shipping_address
console.log('SolidusPaypalCommercePlatform.shippingChange')

url = urlWithParams('/solidus_paypal_commerce_platform/shipping_rates', {
order_id: SolidusPaypalCommercePlatform.current_order_id,
order_token: SolidusPaypalCommercePlatform.current_order_token,
paypal_order_id: paypalData.orderID,
address: shipping_address,
})

const response = await fetch(url, {headers: authHeader()})
const data = await response.json()

if (response.ok) {
return actions.order.patch([data]).catch(function(e) {
console.log('There were some problems with your payment address while trying to patch the order', e);
actions.reject()
})
})
} else {
console.log('There were some problems with your payment address', data);
return actions.reject()
}
}

SolidusPaypalCommercePlatform.verifyTotal = function(paypal_total) {
return Spree.ajax({
url: '/solidus_paypal_commerce_platform/verify_total',
method: 'GET',
data: {
order_id: Spree.current_order_id,
order_token: Spree.current_order_token,
SolidusPaypalCommercePlatform.verifyTotal = async function(paypal_total) {
console.log('SolidusPaypalCommercePlatform.verifyTotal')
const response = await fetch(
urlWithParams('/solidus_paypal_commerce_platform/verify_total', {
order_id: SolidusPaypalCommercePlatform.current_order_id,
order_token: SolidusPaypalCommercePlatform.current_order_token,
paypal_total: paypal_total
},
error: function(response) {
SolidusPaypalCommercePlatform.hideOverlay()
alert('There were some problems with your payment - ' + response.responseJSON.errors.expected_total);
}
})
}), {
headers: authHeader()
})

if (!response.ok) {
SolidusPaypalCommercePlatform.hideOverlay()
alert('There were some problems with your payment - ' + response.responseJSON.errors.expected_total);
}
}

SolidusPaypalCommercePlatform.finalizeOrder = function(payment_method_id, data, actions) {
Expand All @@ -144,26 +192,37 @@ SolidusPaypalCommercePlatform.finalizeOrder = function(payment_method_id, data,
})
}

SolidusPaypalCommercePlatform.advanceOrder = function() {
return Spree.ajax({
url: '/api/checkouts/' + Spree.current_order_id + '/advance',
method: 'PUT',
data: {
order_token: Spree.current_order_token
},
error: function(response) {
SolidusPaypalCommercePlatform.hideOverlay()
alert('There were some problems with your order');
}
})
SolidusPaypalCommercePlatform.advanceOrder = async function() {
console.log('SolidusPaypalCommercePlatform.advanceOrder')
const response = await fetch(
`/api/checkouts/${SolidusPaypalCommercePlatform.current_order_id}/advance`, {
headers: {
...authHeader(),
'Content-Type': 'application/json'
},
method: 'PUT',
body: JSON.stringify({
order_token: SolidusPaypalCommercePlatform.current_order_token
})
})

if (!response.ok) {
SolidusPaypalCommercePlatform.hideOverlay()
alert('There were some problems with your order');
}
}

SolidusPaypalCommercePlatform.addPayment = function(paypal_amount, payment_method_id, data, email) {
return Spree.ajax({
url: '/api/checkouts/' + Spree.current_order_id + '/payments',
SolidusPaypalCommercePlatform.addPayment = async function(paypal_amount, payment_method_id, data, email) {
console.log('SolidusPaypalCommercePlatform.addPayment')
const response = await fetch(
`/api/checkouts/${SolidusPaypalCommercePlatform.current_order_id}/payments`, {
method: 'POST',
data: {
order_token: Spree.current_order_token,
headers: {
...authHeader(),
'Content-Type': 'application/json'
},
body: JSON.stringify({
order_token: SolidusPaypalCommercePlatform.current_order_token,
payment: {
amount: paypal_amount,
payment_method_id: payment_method_id,
Expand All @@ -173,34 +232,43 @@ SolidusPaypalCommercePlatform.addPayment = function(paypal_amount, payment_metho
paypal_funding_source: SolidusPaypalCommercePlatform.fundingSource
}
}
},
error: function(response) {
SolidusPaypalCommercePlatform.hideOverlay()
alert('There were some problems with your payment');
}
})
})

if (!response.ok) {
SolidusPaypalCommercePlatform.hideOverlay()
alert('There were some problems with your payment');
}
}

SolidusPaypalCommercePlatform.updateAddress = function(response) {
var shipping = response.purchase_units[0].shipping;
if (!shipping) return Promise.resolve({});
SolidusPaypalCommercePlatform.updateAddress = async function(payload) {
var shipping = payload.purchase_units[0].shipping
if (!shipping) return Promise.resolve({})

var updated_address = shipping.address;
return Spree.ajax({
url: '/solidus_paypal_commerce_platform/update_address',
method: 'POST',
data: {
address: {
updated_address: updated_address,
recipient: response.payer
var updated_address = shipping.address

const response = await fetch(
'/solidus_paypal_commerce_platform/update_address', {
method: 'POST',
headers: {
...authHeader(),
'Content-Type': 'application/json'
},
order_id: Spree.current_order_id,
order_token: Spree.current_order_token
},
error: function(response) {
SolidusPaypalCommercePlatform.hideOverlay()
message = response.responseJSON;
alert('There were some problems with your payment address - ' + message);
body: JSON.stringify({
address: {
updated_address: updated_address,
recipient: payload.payer
},
order_id: SolidusPaypalCommercePlatform.current_order_id,
order_token: SolidusPaypalCommercePlatform.current_order_token
}),
}
})
)

if (!response.ok) {
SolidusPaypalCommercePlatform.hideOverlay()
const message = await response.text()
console.error('There were some problems with your payment address - ', message);
alert('There were some problems with your payment address - ' + message)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,22 @@
<input type="hidden" name="payment_source[<%= payment_method.id %>][paypal_funding_source]" id="payments_source_paypal_funding_source">

<script>
Spree.current_order_id = "<%= @order.number %>"
Spree.current_order_token = "<%= @order.guest_token %>"
SolidusPaypalCommercePlatform.api_key = "<%= spree_current_user.try(:spree_api_key) %>"
SolidusPaypalCommercePlatform.current_order_id = "<%= @order.number %>"
SolidusPaypalCommercePlatform.current_order_token = "<%= @order.guest_token %>"
</script>

<% unless payment_method.render_only_venmo_standalone? %>
<script>
$( document ).ready(function() {
window.addEventListener('DOMContentLoaded', () => {
SolidusPaypalCommercePlatform.renderButton("<%= payment_method.id %>",<%= raw payment_method.button_style.to_json %>)
})
</script>
<% end %>

<% if payment_method.venmo_standalone_enabled? %>
<script>
$( document ).ready(function() {
window.addEventListener('DOMContentLoaded', () => {
SolidusPaypalCommercePlatform.renderVenmoStandalone("<%= payment_method.id %>",<%= raw payment_method.button_style.to_json %>)
})
</script>
Expand Down
Loading

0 comments on commit b598704

Please sign in to comment.