<commit_before>/**
 * View for the receipt page.
 */
var edx = edx || {};

(function ($, _, _s, Backbone) {
    'use strict';

    edx.commerce = edx.commerce || {};

    edx.commerce.ReceiptView = Backbone.View.extend({
        useEcommerceApi: true,
        ecommerceBasketId: null,
        ecommerceOrderNumber: null,

        initialize: function () {
            this.ecommerceBasketId = $.url('?basket_id');
            this.ecommerceOrderNumber = $.url('?orderNum');
            this.useEcommerceApi = this.ecommerceBasketId || this.ecommerceOrderNumber;
            _.bindAll(this, 'renderReceipt', 'renderError', 'getProviderData', 'renderProvider', 'getCourseData');

            /* Mix non-conflicting functions from underscore.string (all but include, contains, and reverse) into
             * the Underscore namespace.
             */
            _.mixin(_s.exports());

            this.render();
        },

        renderReceipt: function (data) {
            var templateHtml = $("#receipt-tpl").html(),
                context = {
                    platformName: this.$el.data('platform-name'),
                    verified: this.$el.data('verified').toLowerCase() === 'true',
                    is_request_in_themed_site: this.$el.data('is-request-in-themed-site').toLowerCase() === 'true'
                },
                providerId;

            // Add the receipt info to the template context
            this.courseKey = this.getOrderCourseKey(data);
            this.username = this.$el.data('username');
            _.extend(context, {
                receipt: this.receiptContext(data),
                courseKey: this.courseKey
            });

            this.$el.html(_.template(templateHtml)(context));

            this.trackLinks();

            this.trackPurchase(data);

            this.renderCourseNamePlaceholder(this.courseKey);

            providerId = this.getCreditProviderId(data);
            if (providerId) {
                this.getProviderData(providerId).then(this.renderProvider, this.renderError)
            }
        },
        renderCourseNamePlaceholder: function (courseId) {
            // Display the course Id or name (if available) in the placeholder
            var $courseNamePlaceholder = $(".course_name_placeholder");
            $courseNamePlaceholder.text(courseId);

            this.getCourseData(courseId).then(function (responseData) {
                $courseNamePlaceholder.text(responseData.name);
            });
        },
        renderProvider: function (context) {
            var templateHtml = $("#provider-tpl").html(),
                providerDiv = this.$el.find("#receipt-provider");
            context.course_key = this.courseKey;
            context.username = this.username;
            context.platformName = this.$el.data('platform-name');
            providerDiv.html(_.template(templateHtml)(context)).removeClass('hidden');
        },

        renderError: function () {
            // Display an error
            $('#error-container').removeClass('hidden');
        },

        trackPurchase: function (order) {
            window.analytics.track("Completed Order", {
                orderId: order.number,
                total: order.total_excl_tax,
                currency: order.currency
            });
        },

        render: function () {
            var self = this,
                orderId = this.ecommerceOrderNumber || this.ecommerceBasketId || $.url('?payment-order-num');

            if (orderId && this.$el.data('is-payment-complete') === 'True') {
                // Get the order details
                self.$el.removeClass('hidden');
                self.getReceiptData(orderId).then(self.renderReceipt, self.renderError);
            } else {
                self.renderError();
            }
        },

        trackLinks: function () {
            var $verifyNowButton = $('#verify_now_button'),
                $verifyLaterButton = $('#verify_later_button');

            // Track a virtual pageview, for easy funnel reconstruction.
            window.analytics.page('payment', 'receipt');

            // Track the user's decision to verify immediately
            window.analytics.trackLink($verifyNowButton, 'edx.bi.user.verification.immediate', {
                category: 'verification'
            });

            // Track the user's decision to defer their verification
            window.analytics.trackLink($verifyLaterButton, 'edx.bi.user.verification.deferred', {
                category: 'verification'
            });
        },

        /**
         * Retrieve receipt data from Oscar (via LMS).
         * @param  {string} orderId Identifier of the order that was purchased.
         * @return {object} JQuery Promise.
         */
        getReceiptData: function (orderId) {
            var urlFormat = '/shoppingcart/receipt/%s/';

            if (this.ecommerceOrderNumber) {
                urlFormat = '/api/commerce/v1/orders/%s/';
            } else if (this.ecommerceBasketId){
                urlFormat = '/api/commerce/v0/baskets/%s/order/';
            }


            return $.ajax({
                url: _.sprintf(urlFormat, orderId),
                type: 'GET',
                dataType: 'json'
            }).retry({times: 5, timeout: 2000, statusCodes: [404]});
        },
        /**
         * Retrieve credit provider data from LMS.
         * @param  {string} providerId The providerId of the credit provider.
         * @return {object} JQuery Promise.
         */
        getProviderData: function (providerId) {
            var providerUrl = '/api/credit/v1/providers/%s/';

            return $.ajax({
                url: _.sprintf(providerUrl, providerId),
                type: 'GET',
                dataType: 'json',
                contentType: 'application/json',
                headers: {
                    'X-CSRFToken': $.cookie('csrftoken')
                }
            }).retry({times: 5, timeout: 2000, statusCodes: [404]});
        },
        /**
         * Retrieve course data from LMS.
         * @param  {string} courseId The courseId of the course.
         * @return {object} JQuery Promise.
         */
        getCourseData: function (courseId) {
            var courseDetailUrl = '/api/course_structure/v0/courses/%s/';
            return $.ajax({
                url: _.sprintf(courseDetailUrl, courseId),
                type: 'GET',
                dataType: 'json'
            });
        },

        /**
         * Construct the template context from data received
         * from the E-Commerce API.
         *
         * @param  {object} order Receipt data received from the server
         * @return {object} Receipt template context.
         */
        receiptContext: function (order) {<commit_msg>mattdrayer/WL-466: Use LMS Courses API<commit_after>/**
 * View for the receipt page.
 */
var edx = edx || {};

(function ($, _, _s, Backbone) {
    'use strict';

    edx.commerce = edx.commerce || {};

    edx.commerce.ReceiptView = Backbone.View.extend({
        useEcommerceApi: true,
        ecommerceBasketId: null,
        ecommerceOrderNumber: null,

        initialize: function () {
            this.ecommerceBasketId = $.url('?basket_id');
            this.ecommerceOrderNumber = $.url('?orderNum');
            this.useEcommerceApi = this.ecommerceBasketId || this.ecommerceOrderNumber;
            _.bindAll(this, 'renderReceipt', 'renderError', 'getProviderData', 'renderProvider', 'getCourseData');

            /* Mix non-conflicting functions from underscore.string (all but include, contains, and reverse) into
             * the Underscore namespace.
             */
            _.mixin(_s.exports());

            this.render();
        },

        renderReceipt: function (data) {
            var templateHtml = $("#receipt-tpl").html(),
                context = {
                    platformName: this.$el.data('platform-name'),
                    verified: this.$el.data('verified').toLowerCase() === 'true',
                    is_request_in_themed_site: this.$el.data('is-request-in-themed-site').toLowerCase() === 'true'
                },
                providerId;

            // Add the receipt info to the template context
            this.courseKey = this.getOrderCourseKey(data);
            this.username = this.$el.data('username');
            _.extend(context, {
                receipt: this.receiptContext(data),
                courseKey: this.courseKey
            });

            this.$el.html(_.template(templateHtml)(context));

            this.trackLinks();

            this.trackPurchase(data);

            this.renderCourseNamePlaceholder(this.courseKey);

            providerId = this.getCreditProviderId(data);
            if (providerId) {
                this.getProviderData(providerId).then(this.renderProvider, this.renderError)
            }
        },
        renderCourseNamePlaceholder: function (courseId) {
            // Display the course Id or name (if available) in the placeholder
            var $courseNamePlaceholder = $(".course_name_placeholder");
            $courseNamePlaceholder.text(courseId);

            this.getCourseData(courseId).then(function (responseData) {
                $courseNamePlaceholder.text(responseData.name);
            });
        },
        renderProvider: function (context) {
            var templateHtml = $("#provider-tpl").html(),
                providerDiv = this.$el.find("#receipt-provider");
            context.course_key = this.courseKey;
            context.username = this.username;
            context.platformName = this.$el.data('platform-name');
            providerDiv.html(_.template(templateHtml)(context)).removeClass('hidden');
        },

        renderError: function () {
            // Display an error
            $('#error-container').removeClass('hidden');
        },

        trackPurchase: function (order) {
            window.analytics.track("Completed Order", {
                orderId: order.number,
                total: order.total_excl_tax,
                currency: order.currency
            });
        },

        render: function () {
            var self = this,
                orderId = this.ecommerceOrderNumber || this.ecommerceBasketId || $.url('?payment-order-num');

            if (orderId && this.$el.data('is-payment-complete') === 'True') {
                // Get the order details
                self.$el.removeClass('hidden');
                self.getReceiptData(orderId).then(self.renderReceipt, self.renderError);
            } else {
                self.renderError();
            }
        },

        trackLinks: function () {
            var $verifyNowButton = $('#verify_now_button'),
                $verifyLaterButton = $('#verify_later_button');

            // Track a virtual pageview, for easy funnel reconstruction.
            window.analytics.page('payment', 'receipt');

            // Track the user's decision to verify immediately
            window.analytics.trackLink($verifyNowButton, 'edx.bi.user.verification.immediate', {
                category: 'verification'
            });

            // Track the user's decision to defer their verification
            window.analytics.trackLink($verifyLaterButton, 'edx.bi.user.verification.deferred', {
                category: 'verification'
            });
        },

        /**
         * Retrieve receipt data from Oscar (via LMS).
         * @param  {string} orderId Identifier of the order that was purchased.
         * @return {object} JQuery Promise.
         */
        getReceiptData: function (orderId) {
            var urlFormat = '/shoppingcart/receipt/%s/';

            if (this.ecommerceOrderNumber) {
                urlFormat = '/api/commerce/v1/orders/%s/';
            } else if (this.ecommerceBasketId){
                urlFormat = '/api/commerce/v0/baskets/%s/order/';
            }


            return $.ajax({
                url: _.sprintf(urlFormat, orderId),
                type: 'GET',
                dataType: 'json'
            }).retry({times: 5, timeout: 2000, statusCodes: [404]});
        },
        /**
         * Retrieve credit provider data from LMS.
         * @param  {string} providerId The providerId of the credit provider.
         * @return {object} JQuery Promise.
         */
        getProviderData: function (providerId) {
            var providerUrl = '/api/credit/v1/providers/%s/';

            return $.ajax({
                url: _.sprintf(providerUrl, providerId),
                type: 'GET',
                dataType: 'json',
                contentType: 'application/json',
                headers: {
                    'X-CSRFToken': $.cookie('csrftoken')
                }
            }).retry({times: 5, timeout: 2000, statusCodes: [404]});
        },
        /**
         * Retrieve course data from LMS.
         * @param  {string} courseId The courseId of the course.
         * @return {object} JQuery Promise.
         */
        getCourseData: function (courseId) {
            var courseDetailUrl = '/api/courses/v1/courses/%s/';
            return $.ajax({
                url: _.sprintf(courseDetailUrl, courseId),
                type: 'GET',
                dataType: 'json'
            });
        },

        /**
         * Construct the template context from data received
         * from the E-Commerce API.
         *
         * @param  {object} order Receipt data received from the server
         * @return {object} Receipt template context.
         */
        receiptContext: function (order) {
{'fraction_non_alphanumeric': 0.12184565727699531, 'fraction_numerical': 0.003154342723004695, 'mean_word_length': 1.744715119790618, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2002138', 'n_tokens_mistral': 3639, 'n_tokens_neox': 3464, 'n_words': 744}