Completed
Pull Request — development (#110)
by
unknown
03:00
created

js/payone/core/amazonpay.js   B

Complexity

Total Complexity 44
Complexity/F 1.69

Size

Lines of Code 223
Function Count 26

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 1 Features 1
Metric Value
cc 0
c 8
b 1
f 1
nc 3
dl 0
loc 223
rs 8.3396
wmc 44
mnd 3
bc 45
fnc 26
bpm 1.7307
cpm 1.6923
noi 16

11 Functions

Rating   Name   Duplication   Size   Complexity  
A PayoneCheckout.afterChooseMethod 0 4 1
A PayoneCheckout.displayOrderReview 0 19 3
B PayoneCheckout.afterConfirmSelection 0 28 4
A window.onAmazonWidgetsInitialized 0 14 3
A window.onAmazonLoginReady 0 4 1
A window.onDocumentReady 0 18 1
B window.onAmazonPaymentsReady 0 30 2
A PayoneCheckout.afterPlaceOrder 0 5 1
B window.onAmazonPaymentsInvalidPayment 0 35 1
A window.onAmazonPaymentsError 0 12 2
B window.onCheckoutProgress 0 40 2

How to fix   Complexity   

Complexity

Complex classes like js/payone/core/amazonpay.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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
        //noinspection JSUnresolvedFunction, JSUnresolvedVariable
84
        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...
85
        window.location = result['redirectUrl'];
86
    }
87
};
88
89
window.onCheckoutProgress = function (target) {
90
    target.disabled = true;
91
    target.parentElement.addClassName('disabled');
92
    jQuery('#addressBookWidgetCover, #walletWidgetCover').addClass('show');
93
    var Progress = {currentStep: target.getAttribute('id')};
94
    var Agreements = jQuery('#checkout-agreements');
95
    if (Agreements) {
96
        Agreements.serializeArray().each(function(Agreement) {
97
            Progress[Agreement['name']] = Agreement['value'];
98
        });
99
    }
100
    new Ajax.Request(PayoneCheckout.progressAction, {
0 ignored issues
show
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...
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...
101
        method: 'get',
102
        parameters: jQuery.extend({}, PayoneCheckout, Progress),
103
        onSuccess: function (transport) {
104
            if (transport.responseText) {
105
                var Result = JSON.parse(transport.responseText);
106
                if (Result['shouldLogout'] === true) {
107
                    //noinspection JSUnresolvedFunction, JSUnresolvedVariable
108
                    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...
109
                }
110
                if (Result['successful'] === true) {
111
                    var Callback = "after"
112
                        + Progress.currentStep.charAt(0).toUpperCase()
113
                        + Progress.currentStep.slice(1);
114
                    PayoneCheckout[Callback](Result);
115
                } else if (['InvalidPaymentMethod', 'PaymentMethodNotAllowed', 'PaymentPlanNotSet'].indexOf(Result['errorMessage']) != -1) {
116
                    window.onAmazonPaymentsInvalidPayment();
117
                } else {
118
                    alert(Result['errorMessage']);
119
                    jQuery('#placeOrder').attr('disabled', true);
120
                    jQuery('#checkoutStepInit').addClass('allow active').nextAll().removeClass('allow active');
121
                }
122
            }
123
            jQuery('#addressBookWidgetCover, #walletWidgetCover').removeClass('show');
124
            target.parentElement.removeClassName('disabled');
125
            target.disabled = false;
126
        }
127
    });
128
};
129
130
window.onDocumentReady = function () {
131
    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...
132
    jQuery('button.amz').on('click', function (event) {
133
        event.preventDefault();
134
        window.onCheckoutProgress(event.currentTarget);
135
    });
136
    jQuery('li.section').on('click', function (event) {
137
        if (event.currentTarget.hasClassName('allow') &&
138
            !event.currentTarget.hasClassName('active') &&
139
            event.currentTarget.getAttribute('id') !== null
140
        ) {
141
            event.preventDefault();
142
            jQuery('#placeOrder').attr('disabled', true);
143
            jQuery(event.currentTarget).nextAll().removeClass('allow active');
144
            jQuery(event.currentTarget).addClass('allow active');
145
        }
146
    })
147
};
148
149
window.onAmazonWidgetsInitialized = function (orderReference) {
150
    var match,
151
        pl     = /\+/g,
152
        search = /([^&=]+)=?([^&]*)/g,
153
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
154
        query  = window.location.search.substring(1);
155
156
    while (match = search.exec(query)) {
157
        if (decode(match[1]) === "access_token") {
158
            PayoneCheckout.addressConsentToken = decode(match[2]);
159
        }
160
    }
161
    PayoneCheckout.amazonOrderReferenceId = orderReference.getAmazonOrderReferenceId();
162
};
163
164
window.onAmazonLoginReady = function () {
165
    //noinspection JSUnresolvedVariable, JSUnresolvedFunction
166
    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...
167
};
168
169
window.onAmazonPaymentsError = function (error) {
170
    if (error.getErrorCode() === 'BuyerSessionExpired') {
171
        jQuery('#addressBookWidgetCover, #walletWidgetCover')
172
            .css('background', 'lightgrey').addClass('show').delay(15)
173
            .promise().done(function () {
174
                alert(PayoneCheckout.expiredAlert);
175
                window.location.href = PayoneCheckout.cartAction;
176
            });
177
    } else {
178
        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...
179
    }
180
};
181
182
window.onAmazonPaymentsReady = function () {
183
    if (PayoneCheckout.amazonOrderReferenceId !== null) {
184
        return window.onAmazonPaymentsInvalidPayment();
185
    }
186
    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...
187
        sellerId: PayoneCheckout.amazonSellerId,
188
        scope: 'payments:billing_address payments:shipping_address payments:widget profile',
189
        onAddressSelect: function () {
190
            jQuery('#confirmSelection').attr('disabled', true);
191
        },
192
        design: {
193
            designMode: 'responsive'
194
        },
195
        onReady: window.onAmazonWidgetsInitialized,
196
        onError: window.onAmazonPaymentsError
197
    }).bind('addressBookWidgetDiv');
198
    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...
199
        sellerId: PayoneCheckout.amazonSellerId,
200
        scope: 'payments:billing_address payments:shipping_address payments:widget profile',
201
        onPaymentSelect: function () {
202
            jQuery('#confirmSelection').attr('disabled', false);
203
        },
204
        design: {
205
            designMode: 'responsive'
206
        },
207
        onError: function (error) {
208
            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...
209
        }
210
    }).bind('walletWidgetDiv');
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...
211
};
212
213
window.onAmazonPaymentsInvalidPayment = function () {
214
    jQuery('#placeOrder').attr('disabled', true);
215
    jQuery('#checkoutStepInitContent, #chooseMethod').addClass('locked');
216
    jQuery('#addressBookWidgetDiv, #walletWidgetDiv').empty();
217
    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...
218
        displayMode: 'Read',
219
        sellerId: PayoneCheckout.amazonSellerId,
220
        amazonOrderReferenceId: PayoneCheckout.amazonOrderReferenceId,
221
        scope: 'payments:billing_address payments:shipping_address payments:widget profile',
222
        onAddressSelect: function () {
223
            jQuery('#confirmSelection').attr('disabled', true);
224
        },
225
        design: {
226
            designMode: 'responsive'
227
        },
228
        onReady: window.onAmazonWidgetsInitialized,
229
        onError: window.onAmazonPaymentsError
230
    }).bind('addressBookWidgetDiv');
231
    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...
232
        sellerId: PayoneCheckout.amazonSellerId,
233
        amazonOrderReferenceId: PayoneCheckout.amazonOrderReferenceId,
234
        scope: 'payments:billing_address payments:shipping_address payments:widget profile',
235
        onPaymentSelect: function () {
236
            jQuery('#confirmSelection').attr('disabled', false);
237
            jQuery('#checkoutStepInitContent').addClass('solved');
238
        },
239
        design: {
240
            designMode: 'responsive'
241
        },
242
        onError: function (error) {
243
            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...
244
        }
245
    }).bind('walletWidgetDiv');
246
    jQuery('#checkoutStepInit').addClass('allow active').nextAll().removeClass('allow active');
247
};
248
249
jQuery(document).on('ready', window.onDocumentReady);
250