Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 30 ยท Projects

Project: Delivery Estimate Module

Build a complete PrestaShop module that shows an estimated delivery window on the product page, with a cutoff time, business days, holidays, a config page, a template and tests.

Shoppers are more likely to buy when they know when the parcel will arrive. In this project you build a small but complete module, deliverynotice, that shows a message such as "Order within the cutoff time and receive it between Wed 4 Mar and Fri 6 Mar" on every product page. The merchant controls the cutoff time, the handling and transit times and the holidays from a configuration page.

The project brings together several earlier lessons: the module skeleton from Anatomy of a Module, the settings page from A Module Configuration Page, hooks from Common Front Office Hooks, templates from Smarty Templates and Theme Integration, caching from Performance and Caching and tests from Testing Modules. The real module code is shown in read-only blocks, because it needs a PrestaShop shop. The estimator, the validation and the tests are plain PHP and run here on the site, which is exactly why we put the logic there.

The plan

flowchart LR
    P["Product page"] --> H["hookDisplayProductAdditionalInfo"]
    H --> C["Read settings<br/>(Configuration)"]
    C --> E["DeliveryEstimator<br/>(plain PHP)"]
    E --> T["Smarty template"]
    T --> P
    A["Config page"] --> V["Validate and save"]
    V --> C

The hook is thin; the estimator holds the rules and can be tested alone.

The module has these files:

TEXT
deliverynotice/
  deliverynotice.php
  config.xml                 (generated by PrestaShop)
  composer.json
  index.php
  src/DeliveryEstimator.php
  src/SettingsValidator.php
  views/templates/hook/estimate.tpl
  tests/Unit/DeliveryEstimatorTest.php

The rules we implement:

  1. Orders placed up to and including the cutoff time (for example 14:00) are handled the same business day. Later orders, and orders on weekends or holidays, wait for the next business day.
  2. Handling days are extra business days before dispatch (0 means ship on the same day).
  3. Transit is a range, minimum to maximum business days, counted from the dispatch date.
  4. Business days are Monday to Friday, except dates in the merchant's holiday list.

Step 1: the estimator

The estimator has no PrestaShop dependency: it receives its settings in the constructor and the current time as an argument. That makes it deterministic, so a test can say "on Monday at 15:00" without waiting for Monday.

PHP The delivery estimator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the table row by row: an order at 14:00 sharp still ships the same day, an order a minute later waits for the next business day, and a Friday evening order is dispatched on Monday. The holiday on Tuesday 10 March pushes the end of the window for the Friday orders by one day.

The estimator compares times as H:i text. That works because both values are zero-padded 24-hour strings. The settings validator below makes sure the merchant cannot save anything else, such as "2pm".

Step 2: validate the settings

Merchants type the settings, so every value is checked before it is saved. The validator returns a list of error messages; the module shows them as errors on the configuration page and saves nothing when the list is not empty. It is a plain class, so we can test it.

PHP
final class SettingsValidator
{
    /** @return string[] */
    public function validate(array $input): array { /* see the runnable version below */ }
}

Step 3: the module class

The main class registers one display hook and loads and saves the settings. Where a value is read from the request, the module uses Tools::getValue() and gives it to the validator, as in Security in Modules. This code is read-only here:

PHP
<?php
if (!defined('_PS_VERSION_')) {
    exit;
}

require_once __DIR__ . '/src/DeliveryEstimator.php';
require_once __DIR__ . '/src/SettingsValidator.php';

class Deliverynotice extends Module
{
    private const KEYS = [
        'DELIVERYNOTICE_CUTOFF' => '14:00',
        'DELIVERYNOTICE_HANDLING' => '0',
        'DELIVERYNOTICE_MIN' => '2',
        'DELIVERYNOTICE_MAX' => '4',
        'DELIVERYNOTICE_HOLIDAYS' => '',
    ];

    public function __construct()
    {
        $this->name = 'deliverynotice';
        $this->tab = 'shipping_logistics';
        $this->version = '1.0.0';
        $this->author = 'Acme';
        $this->need_instance = 0;
        $this->ps_versions_compliance = ['min' => '8.0.0', 'max' => _PS_VERSION_];
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->trans('Delivery estimate', [], 'Modules.Deliverynotice.Admin');
        $this->description = $this->trans('Shows the expected delivery dates on product pages.', [], 'Modules.Deliverynotice.Admin');
    }

    public function install()
    {
        if (!parent::install() || !$this->registerHook('displayProductAdditionalInfo')) {
            return false;
        }
        foreach (self::KEYS as $key => $default) {
            Configuration::updateValue($key, $default);
        }

        return true;
    }

    public function uninstall()
    {
        foreach (array_keys(self::KEYS) as $key) {
            Configuration::deleteByName($key);
        }

        return parent::uninstall();
    }

    public function getContent()
    {
        $output = '';
        if (Tools::isSubmit('submitDeliverynotice')) {
            $input = [];
            foreach (array_keys(self::KEYS) as $key) {
                $input[$key] = trim((string) Tools::getValue($key));
            }
            $errors = (new SettingsValidator())->validate($input);
            if ($errors) {
                $output .= $this->displayError(implode('<br>', array_map('htmlspecialchars', $errors)));
            } else {
                foreach ($input as $key => $value) {
                    Configuration::updateValue($key, $value);
                }
                $this->_clearCache('*');
                $output .= $this->displayConfirmation($this->trans('Settings updated.', [], 'Admin.Notifications.Success'));
            }
        }

        return $output . $this->renderForm();
    }

    // renderForm() builds a HelperForm with one text input per key,
    // as shown in "A Module Configuration Page".

    public function hookDisplayProductAdditionalInfo($params)
    {
        $holidays = array_filter(array_map('trim', explode(',', (string) Configuration::get('DELIVERYNOTICE_HOLIDAYS'))));
        $estimator = new DeliveryEstimator(
            (string) Configuration::get('DELIVERYNOTICE_CUTOFF'),
            (int) Configuration::get('DELIVERYNOTICE_HANDLING'),
            (int) Configuration::get('DELIVERYNOTICE_MIN'),
            (int) Configuration::get('DELIVERYNOTICE_MAX'),
            $holidays
        );

        $now = new DateTimeImmutable('now', new DateTimeZone(Configuration::get('PS_TIMEZONE') ?: 'UTC'));
        $result = $estimator->estimate($now);

        $template = 'module:deliverynotice/views/templates/hook/estimate.tpl';
        $cacheId = $this->getCacheId($this->name . '|' . $now->format('Ymd') . '|'
            . (int) $estimator->isAfterCutoff($now) . '|' . (int) $this->context->language->id);

        if (!$this->isCached($template, $cacheId)) {
            $this->context->smarty->assign([
                'delivery_today' => $result['today'],
                'delivery_cutoff' => Configuration::get('DELIVERYNOTICE_CUTOFF'),
                'delivery_from' => $this->context->getCurrentLocale()->formatDate($result['from']),
                'delivery_to' => $this->context->getCurrentLocale()->formatDate($result['to']),
            ]);
        }

        return $this->fetch($template, $cacheId);
    }
}

Several choices here deserve a note. The shop's own time zone (PS_TIMEZONE) is used, not the server's, because the cutoff is in the merchant's local time. The cache id contains the date and whether the cutoff has passed, so the stored HTML changes when the answer changes, and the cache is cleared when the settings are saved. The formatDate call is an assumption about the locale API: if your PrestaShop version does not offer a date formatter on the locale, format the date with PHP's IntlDateFormatter or a plain date format instead, and check the API of your version. Uninstalling removes every configuration key so no clutter remains, as taught in Tables, Installers and Upgrades.

Step 4: the template

views/templates/hook/estimate.tpl shows the message. The strings are translatable and use placeholders; the dates are already formatted text, so Smarty escapes them as usual:

SMARTY
<div class="deliverynotice mt-1">
  {if $delivery_today}
    <p>{l s='Order before %time% and it ships today.' sprintf=['%time%' => $delivery_cutoff] d='Modules.Deliverynotice.Shop'}</p>
  {/if}
  <p>
    {l s='Estimated delivery: %from% to %to%.' sprintf=['%from%' => $delivery_from, '%to%' => $delivery_to] d='Modules.Deliverynotice.Shop'}
  </p>
</div>

The next runnable example is a stand-in for the part you cannot run here. It validates the settings, builds the message with a tiny template renderer and shows the three outcomes you would see in a shop: an error list for bad input, a message for a good order before the cutoff and a message after it.

PHP Settings validation and message rendering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The renderer escapes every value with htmlspecialchars, which mirrors what Smarty does in the front office. The bad input shows the validator collecting all problems at once, so the merchant can fix them in one pass.

Step 5: the tests

Because the estimator is plain PHP, its tests are short. A real test file would extend PHPUnit\Framework\TestCase; the tests below use a miniature runner so they run here. The list covers the cutoff boundary on both sides, weekends, a holiday and handling days, which are the edges where date logic breaks.

PHP Tests for the estimator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

If you change a rule later, say to count Saturdays as business days for a merchant who ships on weekends, the first step is a new test that describes the new behavior, then the code change.

Ideas to extend it

  • Show the estimate only for products that are in stock, and a "ships in 2 weeks" message for back-ordered items, reading stock through the product data the hook receives.
  • Add a per-carrier or per-country transit time table in your own database table, with an installer from Tables, Installers and Upgrades.
  • Show a countdown ("order within 2 h 15 min") with a small script registered only on product pages, following Performance and Caching. Remember the page can be cached, so compute the countdown in the browser from a fixed timestamp.
  • Add a multilingual custom message that the merchant can edit, using per-language settings from Translations and Multilingual Modules.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the estimator receive the current time as an argument instead of calling new DateTimeImmutable() inside?

    If the clock is hidden inside the class, a test cannot say 'on Monday at 15:00'. Passing the time in keeps the logic pure and testable.
  2. 2. An order is placed exactly at the cutoff time of 14:00. With the rules of this project, when does it ship?

    Orders up to and including the cutoff are handled the same day, which is why the boundary has its own test.
  3. 3. Which time zone does the module use to decide if the cutoff has passed?

    The cutoff is the merchant's local time, so the module reads the shop's PS_TIMEZONE setting.
  4. 4. Why does the Smarty cache id include the date and whether the cutoff has passed?

    The estimate changes with the day and with the cutoff, so those values must be part of the cache id, together with the language.
  5. 5. What should the module do when the merchant saves invalid settings?

    Validate the whole form first. If there are errors, show them together and keep the old values.

Summary

  • The project is a hook (displayProductAdditionalInfo), a settings page, a plain-PHP estimator and a Smarty template.
  • Keeping the rules in a class that gets its settings and the current time as arguments makes them testable on the site and in PHPUnit.
  • Settings are validated as a whole, saved with Configuration::updateValue(), removed on uninstall, and the template cache is cleared after a save.
  • The cache id includes everything that changes the output: language, date and whether the cutoff has passed.
  • Tests focus on boundaries: the cutoff minute, weekends, holidays and handling days.

Next: Project: Wishlist Lite Module