How-to library · Developer docs

How-to library

Task-shaped pages: a title that starts with a verb, the situation in a few lines, the steps, the working code in both engines, and why this way rather than another. Found from a search, done, and left.

How-to Commerce

Add a bulky items surcharge to shipping rates

Context

Some products cost more to send when a shopper orders many of them: one or two fit the normal parcel, more need a bulky service. A shipping method's Response Job can add a surcharge to every rate the method offers, worked out from the items in the fulfilment, without changing the method's template. The shopper sees the surcharge and its description with each option, it is taxed with the shipping, and the invoice shows it as a line of its own.

Before you start

  • A shipping method of type Template that already offers rates, under Transactions › Shipping › Shipping Methods (Shipping methods and their templates).
  • A product custom field with the identifier maxNonBulkyQuantity, under Customization › Custom Fields (Custom fields), holding how many of the product fit the normal parcel. A product without a value counts as 2, and 0 turns the surcharge off for that product. Variants use their product's value.

Steps

  1. Under Customization › Orchestration, create a job named "Shipping: bulky items surcharge". Switch Synchronous execution on, publish it, and save. It needs no trigger: the shipping method starts it.
  2. Add an HTTP Response action. Set the status code to 200 and the header Content-Type: application/json, and put the code below in its body. The body's output is the job's answer.
  3. Open the shipping method, choose the job as its Response Job, and save.
  4. Create shipping on a test checkout with three of a product whose maxNonBulkyQuantity is 2. Every rate of the method now has a surcharge of 12.99 and the description "Bulky items surcharge (1 × 12.99)". The job's run is under Batch Logs, of the type Shipping method.

Template code

Template code HTTP Response action: Body
{$increments = 0}
{foreach $event->getFulfillment()->getFulfillmentItems() as $fulfillmentItem}
	{$product = $fulfillmentItem->getItem()->getProduct()}
	{if !is_null($product) && !is_null($product->getParent())}{$product = $product->getParent()}{/if}
	{$limit = 0}
	{if !is_null($product)}{$limit = intval($product->getCustomFieldText('maxNonBulkyQuantity', '2'))}{/if}
	{if $limit > 0 && $fulfillmentItem->getQuantity() > $limit}
		{$increments = $increments + ceil(($fulfillmentItem->getQuantity() - $limit) / $limit)}
	{/if}
{/foreach}
{$changes = []}
{if $increments > 0}
	{foreach $event->getRates() as $index => $rate}
		{$changes[] = ['index' => $index, 'surcharge' => $increments * 12.99, 'data' => ['description' => "Bulky items surcharge ({$increments} × 12.99)"]]}
	{/foreach}
{/if}
{$answer = ['rates' => $changes]}
{$answer|json_encode}
{% set increments = 0 %}
{% for fulfillmentItem in event.getFulfillment().getFulfillmentItems() %}
	{% set product = fulfillmentItem.getItem().getProduct() %}
	{% if product is not null and product.getParent() is not null %}{% set product = product.getParent() %}{% endif %}
	{% set limitText = product is not null ? (product.getCustomFieldText('maxNonBulkyQuantity', '2') ?? '') : '' %}
	{% set limit = limitText matches '/^\\d+$/' ? limitText + 0 : 0 %}
	{% if limit > 0 and fulfillmentItem.getQuantity() > limit %}
		{% set increments = increments + ((fulfillmentItem.getQuantity() - limit) / limit)|round(0, 'ceil') %}
	{% endif %}
{% endfor %}
{% set changes = [] %}
{% if increments > 0 %}
	{% for index, rate in event.getRates() %}
		{% set changes = changes|merge([{'index': index, 'surcharge': increments * 12.99, 'data': {'description': 'Bulky items surcharge (' ~ increments ~ ' × 12.99)'}}]) %}
	{% endfor %}
{% endif %}
{{ {'rates': changes}|json_encode }}

Why this and not that

  • The answer changes rates by index. index is a rate's position in getRates(), counted from 0, so the job changes every rate the template created and leaves the rest of each rate as it is. The description is merged into the rate's data.
  • The answer is built as a value. json_encode always prints valid JSON. A JSON answer typed by hand in a Smarty body must be wrapped in {literal}…{/literal}, or Smarty reads its braces as tags and the job fails.
  • A failed job removes the method's rates. If the job fails, is not synchronous or not published, or answers with something that is not JSON, the method offers no rates for that fulfilment, and the shopper sees only the other methods' options. Test it on a development site before you link it on the live one.
  • The Twig version checks the field first. The custom field is text. In Twig, arithmetic on text that is not a number stops the template with an error, so the code checks it holds digits only. In Smarty, intval turns such a value into 0.
  • Variants read their product's field. A variant has no custom fields of its own, so the code takes the product with getParent().
  • The description is public. The shopper reads it through the checkout API and the theme, and it is the text of the invoice's surcharge line. Keep it to words meant for the shopper.
Go deeper

Was this page helpful?

Your answer goes to the docs team.