HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/blijegasten/blijegasten.be/resources/js/shop/components/shoppingcartService.js
import {ErrorResponse} from "../../global/models/errorResponse";
import {CheckoutInformationResponse} from "../../global/models/checkoutInformationResponse";

class ShoppingcartService
{

    /**
     * Validate a product quantity input.
     * Will validate that the quantity is a number and a multiply of the steps if needed
     *
     * @param input
     */
    validateProductQuantityInput(input)
    {
        let quantity = parseInt(input.value);
        let quantityStep = parseInt(input.step);
        const quantityCap = parseInt(input.max);

        // In case the quantity step is undefined or wrong (aka NaN) we force it to one
        if(isNaN(quantityStep)) {
            quantityStep = 1;
        }

        if(isNaN(quantity)) {
            quantity = quantityStep;
            input.value = quantity;
        }

        /**
         * Because it has exceeded the cap we set it to the cap and remove one quantity step.
         * The validateOrRoundUpQuantityToStep function then will automatically round it up.
         */
        if(quantity > quantityCap) {
            quantity = quantityCap - quantityStep;
        }

        /**
         * If the quantityStep is one then we can already return.
         * There is not need to validate if it's a multiply of the quantityStep, because it always is.
         */
        if(quantityStep === 1) return;

        const validatedQuantity = this.validateOrRoundUpQuantityToStep(quantity, quantityStep);

        /**
         * If the validatedQuantity is different the initial quantity, change the input to the validate quantity
         */
        if(quantity !== validatedQuantity) input.value = validatedQuantity;
    }

    /**
     * Iterative function that will validate the given quantity if it a multiply of the steps.
     * Else it will increment and try again till it is.
     * Note: We could also rewrite this into an do/do while function.
     *
     * @param quantity
     * @param step
     * @returns {*}
     */
    validateOrRoundUpQuantityToStep(quantity, step)
    {
        // If not increment the quantity and recall the function
        if(quantity % step !== 0) {
            quantity++;
            return this.validateOrRoundUpQuantityToStep(quantity, step);
        }
        return quantity;
    }

    /**
     * Update the shopping cart items counters
     *
     * @param amount
     */
    updateShoppingCartCounters(amount)
    {
        // If we don't redirect we update the shopping cart amount
        const shoppingCartButtons = document.getElementsByClassName('js-shopping-cart-amount');

        for (let sb = 0; sb < shoppingCartButtons.length; sb++) {
            const shoppingCartButton = shoppingCartButtons[sb];

            // Set shopping cart amount to
            shoppingCartButton.setAttribute('data-items', amount);
        }

    }

    /**
     * Adds a product to the shopping cart
     *
     * @param id
     * @param type
     * @param quantity
     * @param redirect
     */
    _addProductToShoppingcart(id, type, quantity, redirect = true) {
        const self = this;

        return new Promise(function(resolve, reject) {
            Ajax.post(
                '/addProductToShoppingcart',
                {productableId: id, itemType: type, quantity: quantity},
                function (xhr) {

                    if (xhr.status === 200) {

                        // Only redirect if variable is true
                        if (redirect) window.location = xhr.response;
                        else {

                            const shoppingCartButton = document.querySelector('.js-shopping-cart-amount');

                            let shoppingCartAmount = 0;

                            // If already an amount is set, use that instead
                            if (shoppingCartButton.hasAttribute('data-items')) shoppingCartAmount = parseInt(shoppingCartButton.getAttribute('data-items'));

                            // Increment amount by the quantity
                            shoppingCartAmount += parseInt(quantity);

                            self.updateShoppingCartCounters(shoppingCartAmount);
                        }
                        resolve();

                    } else {
                        console.log(id);
                        console.log(type);
                        console.log(quantity);
                        debugger;
                        reject();
                    }
                }
            );
        });
    }

    /**
     * Remove a product from the shopping cart
     *
     * @param id
     * @param type
     */
    _removeItemFromShoppingcart(id,) {
        return new Promise(function(resolve, reject) {
            Ajax.post(
                '/removeItemFromShoppingcart',
                {itemId: id},
                function (xhr) {
                    resolve();
                }
            );
        });
    }

    /**
     * Set the quantity of a shopping cart item
     *
     * @param id
     * @param quantity
     */
    _setItemQuantityInShoppingcart(id, quantity) {
        return new Promise(function(resolve, reject) {
            Ajax.post(
                '/setItemQuantityInShoppingcart',
                {itemId: id, quantity: quantity},
                function (xhr) {
                    resolve();
                }
            );
        });
    }

    getShippingCost(postal, country) {

        return new Promise(function (resolve, reject) {
            Ajax.post(
                '/getShippingCostsByZipcode',
                {
                    'zip': postal,
                    'country': country
                },
                function (xhr) {

                    // let response = JSON.parse(xhr.response);
                    if (ErrorResponse.is(xhr.response, false) === false) {

                        // Convert json and append the status
                        let response = JSON.parse(xhr.response);
                        response.status = xhr.status;

                        resolve(response);

                    } else {
                        let response = ErrorResponse.fromJsonString(xhr.response);
                        reject(response);
                    }
                }
            );
        });
    }

    setShippingCostToFree()
    {
        return new Promise(function(resolve, reject) {
            Ajax.get(
                'setShippingCostToFree',
                function(xhr) {
                    if(xhr.status === 200) resolve();
                    reject();
                }
            );
        });
    }

    /**
     * Get the current cart information
     *
     * @returns {Promise|Promise|Promise}
     */
    getCurrentShoppingCart() {

        return new Promise(function(resolve, reject) {
            Ajax.get(
                'getShoppingCartInformation',
                function(xhr) {
                    let response = JSON.parse(xhr.response);
                    let isErrorResponse = ErrorResponse.is(xhr.response, false);
                    // let isCheckoutInformationResponse = CheckoutInformationResponse.is(xhr.response, false);

                    if(!isErrorResponse) {
                        resolve(response);
                    } else {
                        let response = ErrorResponse.fromJsonString(xhr.response);
                        reject(response);
                    }
                }
            );
        })
    }
}

export { ShoppingcartService }