Free shipping box
Free shipping box
Jan 23, 2023 12:00 AM (2 months ago)

# Free shipping box

This easy to code free shipping box will be nice visual representation for customers, so he can check how much he needs to spend, so he gets free shipping.

Again it is made as standalone module so it can easily implement.

It consists from two main files:

  • default.xml that has display instructions
  • phtml file for HTML markup, and javascript/PHP

default.xml

<body>
        <referenceBlock name="header.container">
            <block name="free.shipping.hyva" after="-"
                   template="Pixel_HyvaFreeShipping::free-shipping.phtml" >
            </block>
        </referenceBlock>
    </body>

free-shipping.phtml

<?php

use Hyva\Theme\ViewModel\Currency;

/** @var ViewModelRegistry $viewModels */
/** @var Currency $currencyViewModel */
$currencyViewModel = $viewModels->require(Currency::class);


$priceTreshold = 0;
$currentCurrencySymbol = $currencyViewModel->getCurrentCurrencySymbol();
?>

<script>

    function freeShipping() {
        return {
            message: '',
            cart: {},
            itemsCount: 0,
            priceTreshold: <?= $priceTreshold ?> || 100,
            freeShipping: false,
            currency: '<?= $currentCurrencySymbol ?>',
            status: 0,

            getData(data) {
                if (data.cart) {
                    this.cart = data.cart;
                    this.checkSubtotal();
                }

            },
            checkSubtotal() {
                const treshold = this.priceTreshold - this.cart.subtotalAmount;
                if (treshold > 0) {
                    this.message = `You are ${this.currency + treshold} short for free shipping!`;
                    this.freeShipping = false;
                    this.status = 100 - treshold;
                } else {
                    this.message = "You meet the condition for free shipping!";
                    this.freeShipping = true;
                    this.status = 100;
                }

            }

        }
    }

</script>
<div x-data="freeShipping()"
     @private-content-loaded.window="getData($event.detail.data)"
     class="free-shipping text-center py-4 max-w-max flex flex-col m-auto">
    <span x-text="message" class="free-shipping-message font-bold"
          :class="{'text-green-600': freeShipping}"></span>
    <div class="w-full my-4 h-3 bg-gray-300 rounded-md truncate">
        <span class="bar block bg-green-600 h-full"
              :style="`width: ${status}%; `"
        ></span>
    </div>
</div>