Completed
Pull Request — development (#82)
by Mario
03:01
created

window.onCheckoutProgress   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 2
c 3
b 0
f 0
nc 2
nop 1
dl 0
loc 39
rs 8.8571

2 Functions

Rating   Name   Duplication   Size   Complexity  
A 0 3 1
B 0 23 5
1
/**
2
 *
3
 * NOTICE OF LICENSE
4
 *
5
 * This source file is subject to the GNU General Public License (GPL 3)
6
 * that is bundled with this package in the file LICENSE.txt
7
 *
8
 * DISCLAIMER
9
 *
10
 * Do not edit or add to this file if you wish to upgrade Payone_Core to newer
11
 * versions in the future. If you wish to customize Payone_Core for your
12
 * needs please refer to http://www.payone.de for more information.
13
 *
14
 * @category        Payone
15
 * @package         js
16
 * @subpackage      payone
17
 * @copyright       Copyright (c) 2017 <[email protected]> - www.fatchip.de
18
 * @author          FATCHIP GmbH <[email protected]>
19
 * @license         <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
20
 * @link            http://www.fatchip.de
21
 */
22
23
/**
24
 * Container with properties and event handlers for
25
 * the interactive Onepage Checkout with Amazon Pay
26
 */
27
var PayoneCheckout = {
28
    amazonOrderReferenceId: null,
29
    addressConsentToken: null,
30
    shippingMethodCode: null,
31
    displayOrderReview: function (result) {
32
        var review = jQuery(result['orderReviewHtml']).filter('#checkout-review-table-wrapper');
33
        var agreements = jQuery(result['orderReviewHtml']).filter('#checkout-agreements');
34
        if (agreements.length === 0) {
35
            agreements = jQuery(result['orderReviewHtml']).find('#checkout-agreements');
36
        }
37
        var orderReview = jQuery('#orderReviewDiv');
38
        if (agreements.length === 1) {
39
            orderReview.html(jQuery.merge(agreements, review));
40
        } else {
41
            orderReview.html(review);
42
        }
43
        var shortDescriptions = orderReview.find('.item-options dd.truncated');
44
        shortDescriptions.hover(function (event) {
45
            jQuery(event.currentTarget).find('.truncated_full_value').addClass('show');
46
        }, function (event) {
47
            jQuery(event.currentTarget).find('.truncated_full_value').removeClass('show');
48
        });
49
    },
50
    afterConfirmSelection: function (result) {
51
        quoteBaseGrandTotal = result['quoteBaseGrandTotal'];
0 ignored issues
show
Bug introduced by
The variable quoteBaseGrandTotal seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.quoteBaseGrandTotal.
Loading history...
52
        checkQuoteBaseGrandTotal = quoteBaseGrandTotal;
0 ignored issues
show
Bug introduced by
The variable checkQuoteBaseGrandTotal seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.checkQuoteBaseGrandTotal.
Loading history...
53
        jQuery('#shippingMethodsDiv').html(result['shippingRatesHtml']);
54
        var availableMethods = jQuery('input[type="radio"][name="shipping_method"]');
55
        if (availableMethods.length > 1) {
56
            availableMethods.on('click', function (event) {
57
                if (event.currentTarget.checked === true) {
58
                    PayoneCheckout.shippingMethodCode = event.currentTarget.getValue();
59
                    window.onCheckoutProgress(jQuery(event.currentTarget).parents('form[id]')[0]);
60
                }
61
            });
62
        }
63
        var checkedMethod = availableMethods.filter(':checked');
64
        if (checkedMethod.length === 1) {
65
            PayoneCheckout.shippingMethodCode = checkedMethod[0].getValue();
66
            jQuery('#placeOrder').attr('disabled', false);
67
        } else if (availableMethods.length === 1) {
68
            // In case there's only one method that's not already checked
69
            var singleMethod = availableMethods.filter(':first');
70
            singleMethod.attr('checked', true);
71
            PayoneCheckout.shippingMethodCode = singleMethod[0].getValue();
72
            window.onCheckoutProgress(singleMethod.parents('form[id]')[0]);
73
        }
74
        this.displayOrderReview(result);
75
        jQuery('#checkoutStepInit').removeClass('active');
76
        jQuery('#checkoutStepFinish').addClass('allow active');
77
    },
78
    afterChooseMethod: function (result) {
79
        this.displayOrderReview(result);
80
        jQuery('#placeOrder').attr('disabled', false);
81
    },
82
    afterPlaceOrder: function (result) {
83
        amazon.Login.logout();
0 ignored issues
show
Bug introduced by
The variable amazon seems to be never declared. If this is a global, consider adding a /** global: amazon */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
84
        window.location = result['redirectUrl'];
85
    }
86
};
87
88
var match, pl = /\+/g, search = /([^&=]+)=?([^&]*)/g,
89
    decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
90
    query = window.location.hash.substring(1) || window.location.search.substring(1),
91
    initiatedByPopup = true;
92
if (window.location.hash.substring(1)) {
93
    initiatedByPopup = false;
94
}
95
96
while (match = search.exec(query)) {
97
  if (decode(match[1]) === "access_token") {
98
    var accessToken = decode(match[2]);
99
    if (typeof accessToken === 'string' && accessToken.match(/^Atza/)) {
100
      document.cookie = "amazon_Login_accessToken=" + accessToken + ";secure";
101
      PayoneCheckout.addressConsentToken = accessToken;
102
    }
103
  }
104
}
105
106
window.onCheckoutProgress = function (target) {
107
    target.disabled = true;
108
    target.parentElement.addClassName('disabled');
109
    jQuery('#addressBookWidgetCover, #walletWidgetCover').addClass('show');
110
    var Progress = {currentStep: target.getAttribute('id')};
111
    var Agreements = jQuery('#checkout-agreements');
112
    if (Agreements) {
113
        Agreements.serializeArray().each(function(Agreement) {
114
            Progress[Agreement['name']] = Agreement['value'];
115
        });
116
    }
117
    new Ajax.Request(PayoneCheckout.progressAction, {
0 ignored issues
show
Unused Code Best Practice introduced by
The object created with new Ajax.Request(PayoneC...alse,false,None,None)}) is not used but discarded. Consider invoking another function instead of a constructor if you are doing this purely for side effects.
Loading history...
Bug introduced by
The variable Ajax seems to be never declared. If this is a global, consider adding a /** global: Ajax */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
118
        method: 'get',
119
        parameters: jQuery.extend({}, PayoneCheckout, Progress),
120
        onSuccess: function (transport) {
121
            if (transport.responseText) {
122
                var Result = JSON.parse(transport.responseText);
123
                if (Result['shouldLogout'] === true) {
124
                    amazon.Login.logout();
0 ignored issues
show
Bug introduced by
The variable amazon seems to be never declared. If this is a global, consider adding a /** global: amazon */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
125
                }
126
                if (Result['successful'] === true) {
127
                    var Callback = "after"
128
                        + Progress.currentStep.charAt(0).toUpperCase()
129
                        + Progress.currentStep.slice(1);
130
                    PayoneCheckout[Callback](Result);
131
                } else if (['InvalidPaymentMethod', 'PaymentMethodNotAllowed', 'PaymentPlanNotSet'].indexOf(Result['errorMessage']) !== -1) {
132
                    window.onAmazonPaymentsInvalidPayment();
133
                } else {
134
                    alert(Result['errorMessage']);
135
                    jQuery('#placeOrder').attr('disabled', true);
136
                    jQuery('#checkoutStepInit').addClass('allow active').nextAll().removeClass('allow active');
137
                }
138
            }
139
            jQuery('#addressBookWidgetCover, #walletWidgetCover').removeClass('show');
140
            target.parentElement.removeClassName('disabled');
141
            target.disabled = false;
142
        }
143
    });
144
};
145
146
window.onDocumentReady = function () {
147
    jQuery.extend(PayoneCheckout, PayoneCheckoutParams);
0 ignored issues
show
Bug introduced by
The variable PayoneCheckoutParams seems to be never declared. If this is a global, consider adding a /** global: PayoneCheckoutParams */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
148
    jQuery('button.amz').on('click', function (event) {
149
        event.preventDefault();
150
        window.onCheckoutProgress(event.currentTarget);
151
    });
152
    jQuery('li.section').on('click', function (event) {
153
        if (event.currentTarget.hasClassName('allow') &&
154
            !event.currentTarget.hasClassName('active') &&
155
            event.currentTarget.getAttribute('id') !== null
156
        ) {
157
            event.preventDefault();
158
            jQuery('#placeOrder').attr('disabled', true);
159
            jQuery(event.currentTarget).nextAll().removeClass('allow active');
160
            jQuery(event.currentTarget).addClass('allow active');
161
        }
162
    });
163
};
164
165
window.onAmazonWidgetsInitialized = function (orderReference) {
166
    PayoneCheckout.amazonOrderReferenceId = orderReference.getAmazonOrderReferenceId();
167
};
168
169
window.onAmazonLoginReady = function () {
170
    amazon.Login.setClientId(PayoneCheckout.amazonClientId);
0 ignored issues
show
Bug introduced by
The variable amazon seems to be never declared. If this is a global, consider adding a /** global: amazon */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
171
    amazon.Login.setUseCookie(true);
172
};
173
174
window.onAmazonPaymentsError = function (error) {
175
    if (error.getErrorCode() === 'BuyerSessionExpired') {
176
        jQuery('#addressBookWidgetCover, #walletWidgetCover')
177
            .css('background', 'lightgrey').addClass('show').delay(15)
178
            .promise().done(function () {
179
                alert(PayoneCheckout.expiredAlert);
180
                window.location.href = PayoneCheckout.cartAction;
181
            });
182
    } else {
183
        console.log(error.getErrorCode() + ': ' + error.getErrorMessage());
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
184
    }
185
};
186
187
window.onAmazonPaymentsReady = function () {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
188
    if (PayoneCheckout.amazonOrderReferenceId !== null) {
189
        return window.onAmazonPaymentsInvalidPayment();
190
    }
191
    new OffAmazonPayments.Widgets.AddressBook({
0 ignored issues
show
Bug introduced by
The variable OffAmazonPayments seems to be never declared. If this is a global, consider adding a /** global: OffAmazonPayments */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
192
        sellerId: PayoneCheckout.amazonSellerId,
193
        scope: 'payments:billing_address payments:shipping_address payments:widget profile',
194
        onAddressSelect: function () {
195
            jQuery('#confirmSelection').attr('disabled', true);
196
        },
197
        design: {
198
            designMode: 'responsive'
199
        },
200
        onReady: window.onAmazonWidgetsInitialized,
201
        onError: window.onAmazonPaymentsError
202
    })  // Bind the widget to the DOM
203
        // element with the given ID.
204
        .bind('addressBookWidgetDiv')
205
        // Reset this widget's flag to
206
        // avoid redrawing, which might
207
        // happen under circumstances.
208
        .renderRequested = initiatedByPopup;
209
    new OffAmazonPayments.Widgets.Wallet({
0 ignored issues
show
Bug introduced by
The variable OffAmazonPayments seems to be never declared. If this is a global, consider adding a /** global: OffAmazonPayments */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
210
        sellerId: PayoneCheckout.amazonSellerId,
211
        scope: 'payments:billing_address payments:shipping_address payments:widget profile',
212
        onPaymentSelect: function () {
213
            jQuery('#confirmSelection').attr('disabled', false);
214
        },
215
        design: {
216
            designMode: 'responsive'
217
        },
218
        onError: function (error) {
219
            console.log(error.getErrorCode() + ': ' + error.getErrorMessage());
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
220
        }
221
    })  // Bind the widget to the DOM
222
        // element with the given ID.
223
        .bind('walletWidgetDiv')
224
        // Reset this widget's flag to
225
        // avoid redrawing, which might
226
        // happen under circumstances.
227
        .renderRequested = initiatedByPopup;
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
228
};
229
230
window.onAmazonPaymentsInvalidPayment = function () {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
231
    jQuery('#placeOrder').attr('disabled', true);
232
    jQuery('#checkoutStepInitContent, #chooseMethod').addClass('locked');
233
    jQuery('#addressBookWidgetDiv, #walletWidgetDiv').empty();
234
    new OffAmazonPayments.Widgets.AddressBook({
0 ignored issues
show
Bug introduced by
The variable OffAmazonPayments seems to be never declared. If this is a global, consider adding a /** global: OffAmazonPayments */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
235
        displayMode: 'Read',
236
        sellerId: PayoneCheckout.amazonSellerId,
237
        amazonOrderReferenceId: PayoneCheckout.amazonOrderReferenceId,
238
        scope: 'payments:billing_address payments:shipping_address payments:widget profile',
239
        onAddressSelect: function () {
240
            jQuery('#confirmSelection').attr('disabled', true);
241
        },
242
        design: {
243
            designMode: 'responsive'
244
        },
245
        onReady: window.onAmazonWidgetsInitialized,
246
        onError: window.onAmazonPaymentsError
247
    })  // Bind the widget to the DOM
248
        // element with the given ID.
249
        .bind('addressBookWidgetDiv')
250
        // Reset this widget's flag to
251
        // avoid redrawing, which might
252
        // happen under circumstances.
253
        .renderRequested = initiatedByPopup;
254
    new OffAmazonPayments.Widgets.Wallet({
0 ignored issues
show
Bug introduced by
The variable OffAmazonPayments seems to be never declared. If this is a global, consider adding a /** global: OffAmazonPayments */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
255
        sellerId: PayoneCheckout.amazonSellerId,
256
        amazonOrderReferenceId: PayoneCheckout.amazonOrderReferenceId,
257
        scope: 'payments:billing_address payments:shipping_address payments:widget profile',
258
        onPaymentSelect: function () {
259
            jQuery('#confirmSelection').attr('disabled', false);
260
            jQuery('#checkoutStepInitContent').addClass('solved');
261
        },
262
        design: {
263
            designMode: 'responsive'
264
        },
265
        onError: function (error) {
266
            console.log(error.getErrorCode() + ': ' + error.getErrorMessage());
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
267
        }
268
    })  // Bind the widget to the DOM
269
        // element with the given ID.
270
        .bind('walletWidgetDiv')
271
        // Reset this widget's flag to
272
        // avoid redrawing, which might
273
        // happen under circumstances.
274
        .renderRequested = initiatedByPopup;
275
    jQuery('#checkoutStepInit').addClass('allow active').nextAll().removeClass('allow active');
276
};
277
278
jQuery(document).on('ready', window.onDocumentReady);
279