No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Cart, checkout and orders in code

addOrderHistory in OpenCart: what happens when the order status changes in 3.0 and 4.1

What addOrderHistory (in 4.1, addHistory) does when an order status changes: fraud check, stock deduction, coupons, rewards, emails and events, and how a module should hook into it correctly.

9 min read OC 3.0 OC 4.1

addOrderHistory in OpenCart is a model method of catalog/model/checkout/order.php through which every order statusA stage of processing: "Pending," "Shipped," "Complete." Custom statuses are added in the dictionary. More in the glossary → change passes: from the checkout step, from the payment systemA service that accepts cards: LiqPay, WayForPay, Monobank, and others. The commission depends on the contract. More in the glossary → callback, and from the admin. In 4.1 it is called addHistory(). The method does more than write a row to order_history. Depending on which status groups the order moves from and into, it runs a fraud check, deducts or restores stock, confirms coupons and bonuses, credits the affiliate commission, and sends emails through core events.

Below is the sequence of actions in OpenCart 3.0 (the code is the same in 3.0.4.1 and 3.0.5.1) and in 4.1 (4.1.0.4), what changed in 4.1, and how a module should react correctly to a status change. The examples are for OpenCart 4.1. In 4.0.x, model triggers and event handling differ.

Who calls the method and with which arguments?

WhatOpenCart 3.0OpenCart 4.1
SignatureaddOrderHistory($order_id, $order_status_id, $comment = '', $notify = false, $override = false)addHistory(int $order_id, int $order_status_id, string $comment = '', bool $notify = false, bool $override = false): void
Returnsnothingnothing
Event triggerscatalog/model/checkout/order/addOrderHistory/before and /aftercatalog/model/checkout/order.addHistory/before and /after

There are three callers. Payment modules on the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary →: for simple payment methods, the controllerCode that receives a request and prepares data. More in the glossary → calls the method on the confirm button; for online payments, in the callback from the bank. Admin: in both branches, the admin does not change the status directly but through the catalog API, the api/order controller (in 3.0 the history method, in 4.1 the internal addHistory()), which calls the same model. That is why the same checks and events run in the admin as on the storefront. Your module: when you need to change the status programmatically, for example after synchronizing with an accounting system.

The $notify and $comment arguments do not affect the method's logic: they are only written to order_history and read by the email handler. $override disables the antifraud module checks; in the admin, this is the "Override" checkbox in the order history form.

Sales → Orders: a status change in the admin goes through the same catalog model method
Sales → Orders: a status change in the admin goes through the same catalog model method · OpenCart 4.1.0.4

What happens inside: the sequence of actions

The key to understanding the method is two status groups under System → Settings, on the Option tab: config_processing_status (processing) and config_complete_status (complete). After installation, the processing group includes the statuses with IDs 5, 1, 2, 12, 3, and the complete group includes 5 and 3. The method compares the group of the old status (from order.order_status_id) with the new one.

Option tab: the
Option tab: the "processing" and "complete" status groups determine when stock is deducted · OpenCart 4.1.0.4
  1. Antifraud. If the customer is not marked as safe (customer.safe), $override is disabled, and the new status is in either group, the check() methods of all enabled fraud extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → are called. A non-zero response overrides the status.
  2. Entering the processing group. If the old status was outside both groups and the new one is inside them: the confirm() methods of the order total modules (coupon, bonuses, balance; a non-zero response again overrides the status), and deduction of product stock and option values from subtract = 1.
  3. Writing the status to order.order_status_id and a new row to order_history.
  4. Leaving the groups. If the old status was in the groups and the new one is not: restoring stock and the unconfirm() methods of the order total modules.
  5. Clearing the product cache so the storefront sees the new stock levels.

catalog/model/checkout/order.php · OpenCart 3.0.5.1 · lines 301–302

			// If current order status is not processing or complete but new status is processing or complete then commence completing the order
			if (!in_array($order_info['order_status_id'], array_merge($this->config->get('config_processing_status'), $this->config->get('config_complete_status'))) && in_array($order_status_id, array_merge($this->config->get('config_processing_status'), $this->config->get('config_complete_status')))) {

This leads to several consequences that explain most of the "strange" complaints. A transition between two statuses within the same group (for example, "Pending" → "Shipped") does not touch stock. Calling the method again with the same status does not deduct the product a second time, because the old status is already in the group. But if a payment module sets a status that is not in any group, stock will not be deducted and the coupon will not be marked as used, even though the order looks placed.

flowchart TD
  A["addOrderHistory / addHistory"] --> B{"Customer safe or override?"}
  B -->|"No, and new status is in groups"| C["fraud check() may change status"]
  B -->|"Yes"| D
  C --> D{"Old outside groups, new inside?"}
  D -->|"Yes"| E["confirm() totals + stock deduction"]
  D -->|"No"| F
  E --> F["Write order.order_status_id and order_history"]
  F --> G{"Old inside groups, new outside?"}
  G -->|"Yes"| H["Stock restore + unconfirm()"]
  G -->|"No"| I["Clear product cache"]
  H --> I

How does 4.1 differ from 3.0?

The skeleton is the same, but 4.1 adds several steps and moves some actions to a different point.

  • Product variants. If the line item is a variant (master_id), 4.1 deducts and restores stock for both the variant itself and the parent product.
  • Affiliate commission. OpenCart 3.0 credits it when entering either group (if config_affiliate_auto is enabled) and removes it when leaving the groups. OpenCart 4.1 credits it only when moving to the complete status, and removes it when the order stops being complete.
  • Subscriptions. In 4.1, moving to a complete status creates or updates a subscription for items with a plan and sets it to an active status (config_subscription_active_status_id). Leaving the complete status suspends it (config_subscription_suspended_status_id).
  • Write order. 3.0 updates order and writes history before the stock restore block; 4.1 does it after all blocks, through editOrderStatusId().
  • The unconfirm signature in order total modules: unconfirm($order_id) in 3.0 and unconfirm(array $order_info) in 4.1.

catalog/model/checkout/order.php · OpenCart 4.1.0.4 · lines 876–886

			// If order status becomes complete status
			if (!in_array($order_info['order_status_id'], (array)$this->config->get('config_complete_status')) && in_array($order_status_id, (array)$this->config->get('config_complete_status'))) {
				// Affiliate add commission if complete status
				if ($order_info['affiliate_id'] && $this->config->get('config_affiliate_auto')) {
					// Add commission if sale is linked to affiliate referral.
					$this->load->model('account/transaction');

					if (!$this->model_account_transaction->getTotalTransactionsByOrderId($order_id)) {
						$this->model_account_transaction->addTransaction($order_info['affiliate_id'], $order_id, $this->language->get('text_order_id') . ' #' . $order_id, (float)$order_info['commission']);
					}
				}

How order total modules implement confirm and unconfirm is covered in the article on order totals.

Where do order emails come from?

The method itself does not send emails. This is done by event handlers that the core registers on installation: mail_order_add (3.0) / mail_order (4.1), and mail_order_alert on …addOrderHistory/before and …addHistory/before respectively. You can see them under Extensions → Events.

Extensions → Events: order emails are sent by mail/order handlers on the before event
Extensions → Events: order emails are sent by mail/order handlers on the before event · OpenCart 4.1.0.4

The mail/order handler works the same way in both branches:

  • if the current order status is 0 and the new one is not, a full confirmation email is sent to the customer, regardless of $notify;
  • if the status is already non-zero and $notify is enabled, a short email about the status change with the comment is sent.

A separate mail/order.alert handler (mail/order/alert in 3.0) sends a notification about the new order to the store owner. Since these are before events, they see the status passed to the method, not the one that will result after antifraud: an order that a fraud module moves to a fraud status will still receive an email with the original status. Mail settings, without which these emails will not be sent at all, are described in the blog post: SMTP and common mail errors in OpenCart.

How should a module react to a status change?

Typical tasks: send the order to a CRM or accounting system, notify in Telegram, create an invoice, release a stock reservation. The right point for them is the after event on the history method: at that moment the status is already written and stock has been changed.

Example: handler after a status change · OpenCart 4.1

// Тригер: catalog/model/checkout/order.addHistory/after
// Дія:    extension/mymodule/event/order.history
public function history(string &$route, array &$args, mixed &$output): void {
	$order_id        = (int)($args[0] ?? 0);
	$order_status_id = (int)($args[1] ?? 0);

	if (!$order_id) {
		return;
	}

	$this->load->model('checkout/order');

	$order_info = $this->model_checkout_order->getOrder($order_id);

	if (!$order_info) {
		return;
	}

	$complete = (array)$this->config->get('config_complete_status');

	if (in_array($order_status_id, $complete)) {
		$this->load->model('extension/mymodule/sync');

		$this->model_extension_mymodule_sync->queue($order_id);
	}
}

For 3.0, the trigger is catalog/model/checkout/order/addOrderHistory/after, the action is extension/module/mymodule/history, and the signature is history(&$route, &$args, &$output). The method also returns nothing there, so check that the order exists via getOrder() as well. How to register an event when installing a module is described in the articles on addEvent and model events.

A few rules that will save you hours of debugging:

  • Check the actual status, not the argument. Antifraud and the coupon confirm() can override the status inside the method. If this is critical, read order.order_status_id in after via getOrder().
  • Be idempotent. Payment systems often send callbacks several times, and a manager may set the same status again. Store what has already been sent in your own table.
  • Do not make long HTTP requests synchronously. The handler runs within the payment callback request or an admin AJAX request; a slow CRM will delay the bank's response and may trigger a repeated callback. Put the task in a queue and process it via cron.
  • Do not change the status by updating order directly. A direct UPDATE bypasses stock deduction, coupons, and emails. Always call the catalog model method. From the 3.0 admin, the catalog/… model is not available, so the status is changed through the catalog API, just as the admin itself does.

If the status did not change at all after payment, the cause is usually not the method but the fact that it was never called: how to track down this problem is described in the article payment went through but the status did not change.

Summary

  • Any status change, whether from checkout, a callback, or the admin, passes through addOrderHistory() in 3.0 or addHistory() in 4.1.
  • Stock, coupons, and bonuses are processed only when entering or leaving the "processing / complete" groups; transitions within the groups do not affect them.
  • Antifraud and the confirm() methods of order total modules can override the status inside the method.
  • 4.1 accounts for variants, credits the partner commission only on the complete status, and manages subscriptions.
  • Emails are sent by the before event handlers: the confirmation on the first non-zero status, and updates only with $notify.
  • For a module, use the after event, make it idempotent, and use a queue instead of synchronous requests; in 3.0, before handlers must return nothing.

The next step is the payment module, which calls this method after payment. All articles in the section are on the page Cart, checkout and orders in code.

FAQ

Why did the product stock go negative?
The method deducts the quantity without checking stock. The check exists only in the cart and at checkout, and the setting that allows checkout without stock turns it off. Two simultaneous orders for the last unit can also both pass the check.
How do I change an order status from my own script without emailing the customer?
Pass notify = false. The confirmation email will still be sent if the current order status is zero, because the mail/order handler sends it on the first non-zero status regardless of notify.
Does stock get restored when an order is deleted in the admin?
In 3.0, yes: the admin deletes orders through the catalog API, and the model first calls addOrderHistory with status 0, which restores stock. In 4.1, the admin delete button calls the sale/order model, which only deletes the rows without restoring stock, so first change the order to a cancelled status.
Can I add a custom status to the processing group?
Yes, create the status under Localisation and mark it in the processing statuses field in the settings. Then moving an order to it will deduct stock and confirm coupons, just like the standard statuses.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.