Skip to content

Incomplete Order Cancellation ​

Flow ID: SY-03 | Module(s): job, eshop, checkout | Complexity: High Last Updated: 2026-11-16 — 4.130.0 resync: the sweep skips any row whose status is not PENDING and getDebrisOrders() now selects status (#737); a REST klarna_payments order Klarna accepts is confirmed to PAID before it can reach the sweep, so the "webhook is the single confirmation point" wording is replaced and the two open Klarna gaps (#1043) are listed; shop_order.tran_ticket is varchar(64) and holds any gateway reference; see decision 737; previous: 2026-11-04 — 4.129.0 resync: the PayByBank expiry cancel now goes through PayByBankGatewayCanceller and the customer cancel through PaymentConfirmationService::cancelByCustomer() (#795); the Piraeus browser cancel return no longer cancels, so this sweep is the only canceller for an abandoned Piraeus order (#958); PaymentConfirmationService.php, AdvCancelIncompleteOrders.php (PayPal Advanced steps), Adv_settings.php, jobs.php and app.php citations re-anchored; previous: 2026-10-13 -- ecommercen#927: the gift-card PayPal sweep decides only on PayPal's answer; order-sweep citations re-anchored

Business Overview ​

When a customer initiates checkout with an online payment method but never completes payment, the order remains in PENDING status indefinitely. Two independent paths handle cancellation:

  1. REST-driven cancellation (PaymentConfirmationService::cancelPayment()): invoked by cancelByCustomer() for the REST endpoint POST /rest/checkout/cancel-payment/{orderId} and for Rest\Order\Controllers\Order (#795, which adds the PayByBank gateway step and can answer 502 payment_cancel_failed), and directly by the PollPayByBankStatus job (the REST webhook family was retired in Advisable-com/ecommercen#721). This is the primary path for REST-placed orders.
  2. Scheduled cleanup (AdvCancelIncompleteOrders cron): runs every 5 minutes as a safety net for stuck PENDING orders that the REST path missed (e.g. abandonment without a gateway callback). It cancels stale PENDING orders, restores stock, returns loyalty points, releases used coupons, and fires ERP/cancel hooks for downstream integrations. An order whose entry_datetime cannot be trusted (NULL, or a legacy '0000-00-00 00:00:00' zero-date row) is skipped, not cancelled -- logged at error level and left PENDING for a human to fix, rather than aborting the whole run or being silently auto-cancelled (Advisable-com/ecommercen#531).

The cron job has special handling for four payment gateways that require external API calls before cancellation:

  • PayByBank -- cancel the pending bank transfer via the PayByBank API before cancelling the order.
  • Iris -- check whether the customer actually paid via the Iris API; if paid, accept the order instead of cancelling.
  • PayPal Advanced -- after a 180-minute grace period, read the PayPal order via the REST API; cancel when PayPal reports no completed or pending capture (or does not know the order), keep the order PENDING when PayPal does not answer or a capture is completed (#916).
  • NexiXPay -- after a configurable grace period elapses (registry XPAY/EXPIRATION, default 180 minutes), query the Nexi XPay API for operationResult; if PAID, accept the order, otherwise cancel.

Architecture ​

AdvCancelIncompleteOrders
  |
  +--> order_model::getDebrisOrders()       query PENDING card-payment orders
  |
  +--> per-gateway handler:
  |     +--> orderEntryDate($order)          SHARED entry_datetime guard (default cards, PayByBank, XPay)
  |     |     null (unparseable) --> return; skip this order, batch continues (#531)
  |     |
  |     +--> cancelOrder($order)             SHARED cancel side-effects (every path)
  |     |     +--> set_status('CANCELED', '+')   cancel + restore product stock + restore gift stock (#688)
  |     |     +--> returnPointsToCustomers()     loyalty point rollback
  |     |     +--> cancelCoupon()                release the applied coupon
  |     |     +--> internalApiOrderCancelHook()  ERP cancel webhook
  |     |
  |     +--> cancelPendingDefaultCards()     timeout-based cancel (most gateways) --> cancelOrder()
  |     +--> cancelPendingPayByBank()        PayByBankGatewayCanceller::cancel() (gateway cancel + pbb_logging row) --> cancelOrder()
  |     +--> handlePendingIrisOrders()       [CANCELED] --> cancelOrder()  |  [PAID] --> update_order(PAID) + ErpHook
  |     +--> handlePendingPaypalAdvancedOrders()  [within 180 min] skip | [no ticket / PayPal 404 / no COMPLETED or PENDING capture] --> cancelOrder() | [no answer / COMPLETED capture] log, stay PENDING
  |     +--> handlePendingXpayOrders()       [not PAID] --> cancelOrder()  |  [PAID] --> update_order(PAID) + ErpHook

Note: every cancellation branch routes through the shared cancelOrder() helper, so all five gateways (default cards, PayByBank, Iris, PayPal Advanced, XPay) release the applied coupon via cancelCoupon() on cancel (Advisable-com/ecommercen#290).

Key Files ​

FileRole
ecommercen/job/libraries/AdvCancelIncompleteOrders.phpJob implementation
application/modules/job/libraries/CancelIncompleteOrders.phpClient-overridable subclass
application/controllers/Cronjob.phpDeprecated manual-trigger route (/cronjob/order_debris); order_debris() delegates to (new CancelIncompleteOrders())->executeCommand([]) instead of duplicating the switch (Advisable-com/ecommercen#500)
ecommercen/eshop/models/Adv_order_model.phpgetDebrisOrders(), set_status()
ecommercen/libraries/internal/OrderCancelHookFireTrait.phpERP cancel hook trait
ecommercen/libraries/internal/OrderForErpHookFireTrait.phpERP acceptance hook trait
src/PaymentGateways/Iris/Iris.phpIris payment gateway client
src/PaymentGateways/PayPal/PayPalRestApi.phpPayPal Advanced REST client (getOrderDetails() marks a PayPal 404 with notFound, PayPalRestApi.php:134-138)
src/PaymentGateways/NexiXPay/XPay.phpNexi XPay payment gateway client (getOrderStatus, mapOperationResultToStatus)
ecommercen/gift_cards/jobs/AdvCancelPendingGiftCards.phpPending gift-card reconciliation (mirrors this flow for gift cards)
ecommercen/eshop/models/Adv_viva_logging_model.phpPayment logging (modern port: src/Domains/Checkout/VivaLogging/ — #148; legacy model still active)
ecommercen/coupons/models/Adv_coupons_model.phpCoupon release

Code Flow ​

1. Order Selection ​

order_model->getDebrisOrders() queries the shop_order table:

sql
SELECT id, order_serial, payway, entry_datetime, coupon_id, tran_ticket, status
FROM shop_order
WHERE status = 'PENDING'
  AND payway IN ('proxypay','paypal','alpha','ethniki','ethniki_nbgpay','ethniki_ee',
                 'eurobank','paybybank','piraeus','apcopay','vivawallet','jcc','iris',
                 'paypaladvanced','stripe','klarna_payments','xpay')
ORDER BY id ASC

The getCardPayWays() helper (ecommercen/helpers/eshop_helper.php) defines the list of eligible payment methods -- 17 entries as of Advisable-com/ecommercen#500, which added ethniki_nbgpay, klarna_payments, and xpay after finding they parked orders at PENDING but were missing from this list (see Known Issues). Cash-on-delivery and bank-transfer orders are excluded because they do not require immediate online payment -- along with delivery, bank_transfer, and paid_at_store, whose Adv_checkout handlers write PENDING_ACCEPTED rather than PENDING, so getDebrisOrders()'s status = 'PENDING' filter never selects them regardless of this list. getCardPayWays() is despite its name not "card payways" but "payways that park an order at PENDING" -- it legitimately includes non-cards (paybybank, iris, klarna_payments). A drift guard, tests/Unit/Helpers/PayWayDebrisCoverageTest.php, pins every allPayWays() entry other than those three PENDING_ACCEPTED payways as required here. That same test class also pins a second, independent invariant added by Advisable-com/ecommercen#530 -- the sibling helper isOrderPaidAtDeliveryByPayWay()'s landing-status partition of allPayWays(), which governs voucher (shipping-label) eligibility rather than debris-cron coverage (see AD-34 Voucher Generation) -- so the file is not debris-cron-only despite its name; the getCardPayWays() behavior described above is unaffected by that second guard.

2. Per-Gateway Handling ​

The job routes each order to the appropriate handler via a switch on payway:

Default Card Gateways (proxypay, paypal, alpha, ethniki, ethniki_nbgpay, ethniki_ee, eurobank, piraeus, apcopay, stripe, klarna_payments) ​

Timeout-based cancellation with gateway-specific grace periods. klarna_payments is routed here on purpose: the modern REST checkout's KlarnaAdapter writes PENDING and needs no gateway probe, so an order that never confirmed is swept by this same 3-hour default. A REST Klarna order that Klarna accepts reaches PAID before it can reach the sweep: synchronously inside place-order on fraud_status: ACCEPTED, or from the notification arm after a pending fraud review (AdvCancelIncompleteOrders.php:86-99, #737; see CF-08 Payment Processing and CF-09 Payment Webhooks). The sweep still cancels an order Klarna never accepted, which makes it a true safety net for Klarna; the two cases it gets wrong are Known Issues 8 and 9 below (#1043). Decision record: 737.

The loop in executeCommand() first skips any order whose status is not PENDING (AdvCancelIncompleteOrders.php:65-71). The query already filters on PENDING; this is defence in depth, because cancelOrder() restores stock, gifts, points and the coupon and must never reverse a paid order, including under a fork's override of the query. A row with no status (a fork's narrower select) is swept as before.

piraeus and apcopay are routed here too, and this sweep is now the only canceller for an abandoned piraeus order: the browser cancel return never cancels it (Adv_checkout.php:2111-2122; only a verified fail POST and the ApcoPay status listener cancel, each after winning claimCanceled()), so an abandoned Piraeus order holds its stock until this sweep cancels it after 180 minutes (#958, docs/decisions/958-payment-return-cancels.md).

entry_datetime is parsed via the shared orderEntryDate($order): ?DateTime helper before any timeout math runs. A NULL or legacy zero-date ('0000-00-00 00:00:00') value returns null from the helper, and the caller returns immediately -- the order is skipped (left PENDING, logged at error level) rather than raising a fatal Error from calling ->add() on a parse failure or, worse, being silently auto-cancelled by a zero-date value that a naive false-only check would treat as valid (Advisable-com/ecommercen#531). The parse itself is Advisable\Domains\Order\Order\EntryDatetime::parse() (src/Domains/Order/Order/EntryDatetime.php), which the REST order resource's pbbExpiresAt uses too; orderEntryDate() adds the skip log on top of it.

GatewayTimeoutRationale
vivawallet2 days (P2D)Viva Wallet redirects can take longer
jcc20 minutes (PT20M)Fast redirect flow
All others3 hours (PT180M)Standard timeout

If now > entry_datetime + timeout, delegates to the shared cancelOrder($order) helper, which runs:

  1. set_status(order_serial, 'CANCELED', false, '+', 'order_debris') -- cancels and restores stock (+ mode)
  2. returnPointsToCustomers() -- rolls back loyalty points if POINT_SYSTEM.IS_ENABLED
  3. cancelCoupon() -- marks the applied coupon unused via coupons_model->markCouponUnused()
  4. internalApiOrderCancelHook() -- fires the InternalApiOrderCancelHook for ERP sync

All five cancellation paths (default cards, PayByBank, Iris, PayPal Advanced, XPay) route their cancel branch through cancelOrder(), so every gateway releases the applied coupon (Advisable-com/ecommercen#290 — previously only this default-cards path did).

PayByBank ​

Uses the configurable expiration from registry PAY_BY_BANK.EXPIRATION (in seconds). The rule lives in ONE modern class, Advisable\Domains\Checkout\Payment\PayByBankExpiration (src/Domains/Checkout/Payment/PayByBankExpiration.php, container-registered in src/Domains/Checkout/container.php): seconds() reads and validates the registry value, expiresAt($entry, $seconds) adds it. The job delegates to it -- payByBankExpirationSeconds() returns payByBankExpiration()->seconds(), and cancelPendingPayByBank() compares now against payByBankExpiration()->expiresAt($entryDate, $this->payByBankExpirationSeconds()), so an override of payByBankExpirationSeconds() in a client fork still decides the window. The REST order resource publishes the same deadline as pbbExpiresAt (computed in Rest\Order\Controllers\Order::prepareForOutput() through the same class), so the client and this job cannot disagree about when a payment code dies. The gateway's own payment_code_life, sent when the code is created, derives from the same value: every PayByBank client is built by PayByBankClientFactory::create() (src/Domains/Checkout/Payment/PayByBankClientFactory.php:15-22), which passes PayByBankExpiration::secondsFrom(): PaymentInitializerFactory (:623), PollPayByBankStatus (:146) and PayByBankGatewayCanceller use the factory directly, and AdvFactories::payByBank() (ecommercen/core/AdvFactories.php:41-45) delegates to it, which covers AdvPayByBankGetStatus and Adv_orders_admin. Adv_order_model::setBatchCanceled() no longer builds a client; it uses the canceller (Adv_order_model.php:3427). And Config::getExpirationHours() rounds it up to whole hours -- so an unset key sends 24 hours, not 0 (or, on the legacy paths, a TypeError out of Config's int constructor that also aborted this job's gateway cancel). The storefront's Pay by Bank success view and the order-created mail still compute the hours they show from the raw PAY_BY_BANK/EXPIRATION setting (/ 3600), outside this rule -- a listed follow-up; client forks override those views.

  1. entry_datetime is parsed via the same shared orderEntryDate() guard described above; a null result skips the order instead of throwing.
  2. Wait until entry_datetime + EXPIRATION has passed. PayByBankExpiration::secondsFrom() validates the registry value to a positive int before it reaches the DateInterval spec string, falling back to PayByBankExpiration::DEFAULT_SECONDS = 86400 (24 hours; the job's PAY_BY_BANK_DEFAULT_EXPIRATION_SECONDS is kept as an alias of it) for any unset, empty, non-numeric or non-positive value -- mirroring xPayExpirationSeconds() (Advisable-com/ecommercen#500, #531). The admin field behind this registry key (saved at ecommercen/settings/controllers/Adv_settings.php:1446, rendered at :1619, validated at :1722) validates with trim alone (no required, no numeric), and no shop ships a default row for it, so this fallback is the only thing standing between an empty/blank admin field and an invalid DateInterval spec ('PTS') that would abort the whole cron run.
  3. Call $this->payByBankGatewayCanceller()->cancel((string) $order->order_serial) (AdvCancelIncompleteOrders.php:154; factory method :424-427, resolved with di()->get(PayByBankGatewayCanceller::class)). It cancels at PayByBank and returns a PayByBankCancelOutcome (Cancelled, Refused or Unreachable); the sweep ignores the outcome (#795).
  4. The canceller writes the pbb_logging row (called_for = 'cancel') through PayByBankLog::recordCancel() (best effort, src/Domains/Checkout/Payment/PayByBankLog.php:16-29).
  5. Cancel via the shared cancelOrder() helper -- set_status + restore stock, return loyalty points, release the applied coupon, fire the ERP cancel hook (whatever the gateway answered, including Refused for an order the gateway reports paid; the log row records the response).

Iris ​

Checks actual payment status before deciding:

  1. Load Iris order record via order_model->getIrisRecordsByOrderId().
  2. Call Iris->getOrderStatus(['orderId' => irisOrderId]) to query Iris.
  3. Interpret response via IrisHelper::interpretIrisResponse():
    • PENDING or no response: skip (try again on next run).
    • CANCELED: cancel via cancelOrder() -- cancel, return points, release the applied coupon, fire cancel hook.
    • PAID: accept the order -- update status to PAID, set meta_data to job:CancelIncompleteOrders:handlePendingIrisOrders, and fire the ERP acceptance hook (internalApiOrderForErpHook()).

PayPal Advanced ​

Asks PayPal about the order, but only after a grace period (handlePendingPaypalAdvancedOrders(), ecommercen/job/libraries/AdvCancelIncompleteOrders.php:223-274; #916). The buyer may still be on PayPal's approval page, and a headless order is only captured when the client calls confirm-payment (CF-08), so the job no longer cancels a young order:

  1. Entry-datetime guard: entry_datetime is parsed via the shared orderEntryDate() guard; a null result skips the order (:225-229).
  2. Grace period: if now <= entry_datetime + PAYPAL_ADVANCED_GRACE ('PT180M', :34, the same 180 minutes as cancelPendingDefaultCards()), return and let the next run retry (:231-233).
  3. No ticket: an empty tran_ticket means PayPal never created the order, so cancel via cancelOrder() (:235-238).
  4. Read the order: payPalOrderDetails() (:282-287) calls PayPalRestApi->getOrderDetails(tran_ticket). A PayPal 404 comes back as notFound and the order is cancelled, because PayPal does not know it (:242-245). Any other failure (timeout, token failure, other HTTP error) has no status; it is logged and the order stays PENDING for the next run (:247-256).
  5. Capture statuses: the status of every capture in every purchase_units[].payments.captures[] is collected (:258; the old code looked at the first capture of the first unit only).
  6. COMPLETED capture on a still-PENDING order: the buyer was charged but the order never confirmed. The job logs at error level and leaves the order PENDING for a manual decision or a refund; it never cancels it (:260-269).
  7. Otherwise: if no capture is PENDING, cancel via cancelOrder() -- cancel, return points, release the applied coupon, fire cancel hook; a PENDING capture is left for a later run (:271-273).

Unlike Iris and XPay the job never accepts a PayPal order: acceptance of a headless order is confirm-payment's capture-and-settle step (CF-08), and of a storefront order the browser capture.

NexiXPay ​

Verifies payment status with Nexi XPay before deciding, but only after a grace period elapses -- added by Advisable-com/ecommercen#500, since making the previously-unreachable xpay branch reachable would otherwise have started cancelling orders mid-redirect:

  1. Entry-datetime guard: entry_datetime is parsed via the shared orderEntryDate() guard described under Default Card Gateways above; a null result skips the order before the grace-period math below runs.
  2. Grace-period guard (xPayExpirationSeconds(), ecommercen/job/libraries/AdvCancelIncompleteOrders.php): if now <= entry_datetime + XPAY.EXPIRATION seconds, return immediately and let the next 5-minute run retry. The window defaults to 10800 seconds (180 minutes) and is read from registry XPAY/EXPIRATION; any unset, empty, non-numeric, or non-positive registry value falls back to the default rather than reaching the DateInterval spec string (which would throw and abort the whole cron run). There is no admin settings field for this key -- it is registry-only. PAY_BY_BANK/EXPIRATION is validated the same way by payByBankExpirationSeconds() (Advisable-com/ecommercen#531) -- see the PayByBank section above.
  3. Call XPay->getOrderStatus(order_serial) to fetch the Nexi XPay order record
  4. Map operationResult through XPay->mapOperationResultToStatus() to a normalized status
  5. If response is empty or status is not PAID: cancel via the shared cancelOrder() helper -- set_status + return points + release coupon + ERP cancel hook
  6. If status is PAID (payment succeeded but customer never returned): update_order(status=PAID) + internalApiOrderForErpHook()

3. REST-Driven Cancellation ​

PaymentConfirmationService::cancelPayment() (src/Domains/Checkout/PaymentConfirmationService.php:159-211) is the primary cancellation path for REST-placed orders. The REST webhook controller (src/Rest/Webhooks) was retired in Advisable-com/ecommercen#721 and no longer exists. Current callers:

  • REST endpoint: POST /rest/checkout/cancel-payment/{orderId} — Checkout::cancelPayment() (src/Rest/Checkout/Controllers/Checkout.php:1965, cancelByCustomer() call at :2005-2020, 502 handling at :2010-2019).
  • Order REST controller: Rest\Order\Controllers\Order (src/Rest/Order/Controllers/Order.php:319), which treats only cancelByCustomer(...) === PaymentTransition::Applied as success (:319-322), so a race loser gets 400 "cannot be cancelled in its current status" even though the order is CANCELED; a PaymentCancelFailedException becomes 502 payment_cancel_failed (Order.php:323-333).
  • PayByBank polling job: PollPayByBankStatus (src/Domains/Checkout/Jobs/PollPayByBankStatus.php:107-110 for orders the gateway no longer knows, :128-131 for cancelled gateway statuses).

The method (since #880; the REST-facing contract and race answers are documented in CF-08 Payment Processing):

  1. Customer path (cancelByCustomer(), :134-151): for a PENDING paybybank order it first calls PayByBankGatewayCanceller::cancel() outside the database transaction; if the outcome is not Cancelled and the order is still PENDING it throws PaymentCancelFailedException (src/Domains/Checkout/Exceptions/PaymentCancelFailedException.php, ERROR_CODE = 'payment_cancel_failed') and the order stays PENDING with its stock reserved; otherwise it delegates to cancelPayment() (#795).
  2. Atomic conditional write (:172-180): inside transactional(...) it runs transitionStatus($orderId, 'PENDING', 'CANCELED', ...) (:173) and, only if that flip won, $this->stockService->restoreStockForOrder($orderId) (:177) — equivalent to the cron's set_status('CANCELED', '+') stock-restore path. If the stock release fails the whole cancel rolls back, the order stays PENDING and a RuntimeException is thrown (:182-184).
  3. Race loser (:186-192): a call whose flip did not win does nothing and returns PaymentTransition::AlreadyApplied (the order is already CANCELED) or PaymentTransition::Rejected.
  4. Event dispatch (:201): only the winner dispatches the OrderCanceled event, which triggers registered listeners for loyalty-point restore, coupon-usage decrement, and gift-stock restore (RestoreGiftStockOnCanceledListener, src/Domains/Order/Event/Listeners/RestoreGiftStockOnCanceledListener.php -- Advisable-com/ecommercen#688). It fires after the cancel transaction has committed.
  5. Returns PaymentTransition::Applied (:210).

The AdvCancelIncompleteOrders cron acts as the safety net for orders where no cancel/confirm signal was received (no REST cancel-payment call, no gateway callback: customer abandoned the gateway page, network timeout, gateway outage). It selects only status = 'PENDING' orders, so any order already cancelled by cancelPayment() is skipped automatically.

4. Stock Restoration ​

The set_status() method's stockMode = '+' parameter triggers returnOrderStock(), which iterates the order basket and adds quantities back to product_codes.stock.

Since Advisable-com/ecommercen#688, set_status() also restores gift stock under a narrower gate -- stockMode === '+' and status === 'CANCELED' (ecommercen/eshop/models/Adv_order_model.php:1839-1841): it calls restoreOrderGifts($orderSerial) (:1033-1075), which claims the once-only shop_order.gifts_applied marker via claimGiftsApplied() (:1127-1139) and, on a successful claim, restores each gift's counter via gifts_model->restoreCounter(). Because every legacy cancellation path documented in this flow converges on the shared cancelOrder() helper (cancelOrder() at ecommercen/job/libraries/AdvCancelIncompleteOrders.php:188, set_status call at :190), which calls set_status($order->order_serial, 'CANCELED', false, '+', 'order_debris'), gift stock is restored for every gateway (default cards, PayByBank, Iris, PayPal Advanced, XPay) on cancellation.

5. Loyalty Point Rollback ​

When POINT_SYSTEM.IS_ENABLED is true in registry, the job loads the loyalty library and calls returnPointsToCustomers() to credit back any points the customer spent on the order.

Data Model ​

Primary Table: shop_order ​

ColumnTypeRole
idintPK
order_serialvarcharHuman-readable order number
statusvarcharCurrent status (filtered for PENDING)
paywayvarcharPayment gateway identifier
entry_datetimedatetimeOrder creation timestamp (used for timeout)
coupon_idint/nullFK to applied coupon
tran_ticketvarchar(64)/nullGateway reference of any payway (Klarna order id, Stripe session id, Viva order code, PayPal order id, ...); widened from varchar(32) and indexed by database/migrations/20261110120000_widen_and_index_shop_order_tran_ticket.php (#737)
canceled_datedatetimeSet on cancellation
meta_datatextAudit trail for status changes
gifts_appliedtinyint(1)1 while gift stock is currently consumed for this order; cleared by claimGiftsApplied() on restore (database/migrations/20260831120000_add_gifts_applied_to_shop_order.php:13, Advisable-com/ecommercen#688)
TableRole
shop_order_basketOrder line items (stock restoration source)
product_codesProduct SKU stock levels
iris_ordersIris payment gateway order mapping
pbb_loggingPayByBank API call history (database/initial/initial.sql:804; written by PayByBankLog, PayByBankLog.php:11)
couponsCoupon usage tracking
customer_pointsLoyalty point ledger

Configuration ​

Job Scheduling (application/config/jobs.php) ​

php
['command' => 'CancelIncompleteOrders', 'schedule' => '*/5 * * * *', 'graceTime' => 300, 'retryTimes' => 3]

Runs every 5 minutes in the core queue. Enabled by default.

Registry Settings ​

GroupKeyPurpose
PAY_BY_BANKEXPIRATIONTimeout in seconds before PayByBank orders are cancelled (default 86400 = 24 hours if unset, empty, non-numeric, or non-positive -- PayByBankExpiration::secondsFrom(), src/Domains/Checkout/Payment/PayByBankExpiration.php:74-81 (the <= 0 test is at :76); validated by payByBankExpirationSeconds(), Advisable-com/ecommercen#531; has an admin field, ecommercen/settings/controllers/Adv_settings.php:1722, but it is validated with trim alone and no shop ships a default row)
XPAYEXPIRATIONGrace period in seconds before a PENDING xpay order is probed against the Nexi API (default 10800 = 180 minutes if unset, empty, non-numeric, or non-positive). No admin UI field -- registry-only (Advisable-com/ecommercen#500).
POINT_SYSTEMIS_ENABLEDWhether to rollback loyalty points on cancellation

Environment / Gateway Configuration ​

  • Iris: configured via getIrisSettings() helper
  • PayPal Advanced: configured via getPaypalAdvancedSettings() helper; the PayPalRestApi client fetches its access token on first use and bounds every request (15 s total, 3 s connect, constructor defaults PayPalRestApi.php:31-32)
  • PayByBank: PayByBankGatewayCanceller -> PayByBankClientFactory::createIfConfigured() (src/Domains/Checkout/Payment/PayByBankClientFactory.php:27-40)
  • NexiXPay: configured via getXPaySettings() in ecommercen/helpers/registry_helper.php:585-595; XPay client lazy-instantiated via xPay() getter; grace period read from registry XPAY/EXPIRATION via xPayExpirationSeconds()

Client Extension Points ​

  1. Override the job class: Extend AdvCancelIncompleteOrders in application/modules/job/libraries/CancelIncompleteOrders.php to:

    • Add custom payment gateway handlers (new case in the switch)
    • Change timeout logic for specific gateways
    • Add custom notification on cancellation
    • If it overrides getDebrisOrders() (Adv_order_model.php:3444-3454), keep status in the select: the loop's PENDING skip guard (:65-71) only protects a paid order when the row carries status
  2. Override getCardPayWays(): Redefine in application/helpers/ (the base is function_exists()-guarded) to include or exclude payment methods from debris cleanup. Caution: omitting a payway whose checkout handler writes PENDING silently strands its orders forever -- no stock restore, no loyalty-points return, no coupon release, no ERP cancel hook, and no error raised anywhere. This is exactly how xpay, klarna_payments, and ethniki_nbgpay drifted out of coverage upstream (Advisable-com/ecommercen#500); a client override does not automatically inherit that fix and must independently include any PENDING-writing payway it adds.

  3. Custom ERP hooks: The InternalApiOrderCancelHook and InternalApiOrderForErpHook fire webhooks that ERP integrations can subscribe to for order sync.

  4. Adjust schedule: Modify the cron expression and grace time in jobs.php.

Business Rules ​

RuleDescription
Card payments onlyOnly orders with online payment methods (from getCardPayWays()) are considered
Gateway-specific timeoutsViva Wallet: 2 days, JCC: 20 min, XPay: registry XPAY.EXPIRATION (default 3 hours), PayPal Advanced: 3 hours before PayPal is asked (PAYPAL_ADVANCED_GRACE, #916), all others: 3 hours
PayByBank respects registryTimeout driven by PAY_BY_BANK.EXPIRATION registry value (seconds); defaults to 86400 (24 hours) for any unset/empty/non-numeric/non-positive value (Advisable-com/ecommercen#531, PayByBankExpiration.php:76)
XPay respects registryGrace period driven by XPAY.EXPIRATION registry value (seconds); no admin UI field, defaults to 180 minutes for any unset/invalid value
Untrustworthy entry_datetime = skipAn order whose entry_datetime fails to parse cleanly (NULL or a legacy zero-date row) is left PENDING and logged, never auto-cancelled and never allowed to abort the run (Advisable-com/ecommercen#531)
Iris may acceptIf Iris reports PAID, the order is accepted rather than cancelled
Iris PENDING = skipPENDING Iris orders are retried on the next job run
PayPal Advanced acts on PayPal's own answerAfter the 180-minute grace the order is cancelled only when it has no ticket, PayPal answers 404, or PayPal reports no completed or pending capture; no answer keeps it PENDING and a completed capture is logged, never cancelled (#916)
XPay may acceptIf Nexi XPay reports PAID, the order is accepted; otherwise cancelled -- but only once the XPAY.EXPIRATION grace period has elapsed, so an order whose shopper is still mid-redirect on the Nexi hosted page is left alone for the next run.
Stock always restoredset_status() with stockMode='+' restores product stock on cancellation; when status === 'CANCELED' it also restores gift stock via restoreOrderGifts() (Advisable-com/ecommercen#688)
Coupon releasedApplied coupons are marked unused so the customer can reuse them
Points returnedLoyalty points are credited back when POINT_SYSTEM.IS_ENABLED
ERP notificationCancel and accept hooks fire for all cancellations/acceptances
IdempotentOnly PENDING orders are selected; once cancelled, they will not be reprocessed

Gift Card Reconciliation ​

A parallel job, AdvCancelPendingGiftCards (ecommercen/gift_cards/jobs/AdvCancelPendingGiftCards.php), reconciles PENDING gift-card orders on the same cadence. It differs from the main flow in three ways:

  1. Blanket cancel for most payways: gift-card orders older than giftCardDateTimeIntervalToDrop are mass-cancelled via gift_card_orders_model->cancelPending(), except those paid with iris, paypaladvanced, or xpay (:44).
  2. API-verified payways route to dedicated handlers:
    • cancelPendingIrisOrders() -- uses Iris->getOrderStatus() and IrisHelper::interpretIrisResponse()
    • cancelPendingPaypalAdvancedOrders() -- decides only on PayPal's own answer, as the order sweep does (AdvCancelPendingGiftCards.php:227-271, ecommercen#927): an empty tran_ticket (ecommercen#416) or PayPal's 404 cancels; a failed read (no status) is logged and the gift card stays pending; a COMPLETED capture on any purchase unit accepts it (PayPalCaptureStatuses::of()); a PENDING capture waits; otherwise it is cancelled. payPalOrderDetails() (:279-284) is the test seam.
    • cancelPendingXpayOrders() -- uses XPay->getOrderStatus() and XPay->mapOperationResultToStatus() (:286-311)
  3. Accept/cancel uses gift-card model methods: gift_card_orders_model->acceptGiftCard($id) and cancelGiftCard($id) instead of set_status().
  4. giftCardDateTimeIntervalToDrop is now validated the same way the main flow validates XPAY/PAY_BY_BANK EXPIRATION: the new dateTimeIntervalToDrop() helper guards a missing/empty/non-string config value and a malformed DateInterval spec, falling back to DEFAULT_DATE_TIME_INTERVAL_TO_DROP = 'PT180M' (3 hours -- identical to the value this repo's application/config/app.php:574 ships) and logging at error level (Advisable-com/ecommercen#531). The live vector is a client fork whose application/config/app.php predates the giftCardDateTimeIntervalToDrop key: previously, config->item() returning null fed straight into new \DateInterval(null), which throws before the job's first query runs, aborting the entire gift-card reconciliation run.

Known Issues & Security Gaps ​

  1. No grace period for Iris (open): unlike vivawallet (2 days) and now xpay (registry XPAY/EXPIRATION, default 180 minutes -- closed for XPay by Advisable-com/ecommercen#500), a PENDING iris order hits the Iris API on every cron run from creation, so if the customer is still completing the Iris flow the order could in principle be flagged CANCELED before they finish. Not yet fixed; this issue previously also covered XPay, which is now resolved.

  2. xpay/klarna_payments/ethniki_nbgpay payway-coverage gap -- resolved (Advisable-com/ecommercen#500): these three branches were previously unreachable dead code -- getCardPayWays() (ecommercen/helpers/eshop_helper.php) omitted all three, so the sole order source getDebrisOrders() could never select their PENDING orders even though the job's switch already handled them (the gift-card job's AdvCancelPendingGiftCards special-cased xpay the whole time, underscoring that it was a registered, live payway). Fixed by adding all three to getCardPayWays(), bringing it to 17 entries; a drift guard (tests/Unit/Helpers/PayWayDebrisCoverageTest.php) now pins the invariant. That same test class was later extended (Advisable-com/ecommercen#530, see item 4 below) with a second, independent invariant over the sibling voucher-eligibility helper -- the class name predates that second guard and is kept as-is since released changelogs already cite it by name.

  3. Duplicate XPay handler in deprecated Cronjob::order_debris() -- resolved (Advisable-com/ecommercen#500): the manually-triggerable route used to carry a full duplicate of the switch and per-gateway handlers -- including the same then-dead xpay branch -- at permanent risk of drifting from the job (the #290 coupon-release fix had already landed only in the job, not this duplicate). order_debris() now delegates to (new CancelIncompleteOrders())->executeCommand([]), so the route and the scheduled job are guaranteed to behave identically going forward.

  4. Observation: getCardPayWays() and isOrderPaidAtDeliveryByPayWay()'s exclusion list are now set-identical -- not a cue to unify them. After Advisable-com/ecommercen#530, both lists hold the same 17 payways, because both independently partition allPayWays() along the same PENDING-vs-PENDING_ACCEPTED landing-status boundary that Adv_checkout's handlers actually produce (see AD-34 Voucher Generation). This is a deliberate observation, not a design invariant to enforce, and unifying the two lists is explicitly out of scope here: a client fork that overrides only one of the two helpers would silently diverge from the other, a client-override migration hazard. If unification is ever pursued, it needs its own scoped issue with an explicit override-migration plan.

  5. One bad entry_datetime aborting the whole cron run -- resolved (Advisable-com/ecommercen#531): cancelPendingDefaultCards(), cancelPendingPayByBank(), and handlePendingXpayOrders() each fed entry_datetime into DateTime::createFromFormat() and called ->add() on the result one line later. entry_datetime is datetime DEFAULT NULL, so NULL (or an empty/garbage value) is structurally possible; for those, createFromFormat() returns false, and false->add() is a fatal Error in PHP 8 that killed the whole executeCommand() foreach -- stranding every remaining PENDING order in that run (stock reserved, coupons held, points withheld) and re-fataling every 5 minutes until the row was hand-fixed. A legacy zero-date row ('0000-00-00 00:00:00') is a second, distinct bad-data shape: createFromFormat() does not return false for it -- it returns a valid DateTime rolled back to -0001-11-30 with a "parsed date was invalid" warning from DateTime::getLastErrors(). A false-only guard would have let that object through as valid and silently auto-cancelled the order, since a year -0001 timestamp trivially clears every grace window. A related hazard in the same file: cancelPendingPayByBank() interpolated the raw PAY_BY_BANK/EXPIRATION registry value into a DateInterval spec with no validation, so an empty/non-numeric value (reachable via the unvalidated pay_by_bank_expiration admin field) built an invalid spec and threw, the same batch-abort. Fixed by the shared orderEntryDate() guard (which inspects DateTime::getLastErrors() in addition to the return value, so both bad-data shapes are treated as unparseable and the order is skipped rather than cancelled or auto-cancelled) and by payByBankExpirationSeconds(), mirroring xPayExpirationSeconds() (#500). The gift-card sibling job AdvCancelPendingGiftCards had the analogous hazard around giftCardDateTimeIntervalToDrop, fixed the same way.

  6. Gift-card sweep cancelling on a PayPal read failure -- resolved (Advisable-com/ecommercen#927): AdvCancelPendingGiftCards::cancelPendingPaypalAdvancedOrders() read only the first capture of the first purchase unit and cancelled on anything but COMPLETED, so a timeout, a token failure or a capture held for review cancelled a gift card PayPal may have been paid for. It now applies the order sweep's rules (see the gift-card bullet above).

  7. A PayPal capture without a confirmed order needs a human (by design): when the sweep finds a COMPLETED capture on an order still PENDING after 180 minutes it only logs at error level (AdvCancelIncompleteOrders.php:260-269). Nothing queues the order for review, so the log line is the only signal.

  8. The sweep can cancel a Klarna order still in fraud review (open, #1043): Klarna's pending fraud review exists only for US/UK merchants and can outlast the 180-minute timeout. The sweep then cancels the order (AdvCancelIncompleteOrders.php:91-99); a later ACCEPTED notification finds it CANCELED, confirmPayment() returns Rejected, and the handler only logs at error level and answers 200 (src/Domains/Checkout/Payment/KlarnaNotificationHandler.php:108-117).

  9. A Klarna confirmation that threw is cancelled by the sweep (open, #1043): if confirmPayment() throws inside PlaceOrderService after Klarna charged the customer, the order stays PENDING and no webhook follows for an order Klarna accepted synchronously (PlaceOrderService.php:874-885, logged with log_message('error', ...)); the sweep cancels it once the timeout passes.

Tests ​

Test FileCoverage
tests/Unit/Jobs/AdvCancelIncompleteOrdersTest.phpRegression coverage for #290 (every cancellation path releases the applied coupon via the shared cancelOrder() helper), #500 (xpay / klarna_payments / ethniki_nbgpay routing and the XPAY/EXPIRATION grace window) and #531 (an untrustworthy entry_datetime is skipped, and PAY_BY_BANK/EXPIRATION is validated before it reaches a DateInterval spec). Isolated unit tests with stubbed collaborators
tests/Unit/Jobs/AdvCancelIncompleteOrdersTest.php (PayPal cases)#916: the 180-minute grace, PayPal-404 cancel, unknown answer keeps PENDING, sum-of-captures and completed-capture-logged paths of handlePendingPaypalAdvancedOrders()
tests/Unit/Jobs/AdvCancelIncompleteOrdersTest.php (#737 cases)A paid klarna_payments order in the debris set is never cancelled (a_paid_klarna_order_in_the_debris_set_is_never_cancelled, :748) while a PENDING one still is
tests/Unit/Jobs/AdvCancelIncompleteOrdersTest.php (PayByBank cases)#795: past the deadline cancelPendingPayByBank() delegates the gateway call to PayByBankGatewayCanceller and still cancels locally whatever it answers
tests/Unit/Domains/Checkout/Payment/PayByBankGatewayCancellerTest.phpPayByBankGatewayCanceller::cancel() outcomes (Cancelled, Refused, Unreachable), the paid-status probe and the pbb_logging cancel row (#795)
tests/Legacy/Eshop/AdvOrderModelBatchCancelPayByBankTest.phpThe admin batch cancel (setBatchCanceled()) goes through the canceller (#795)
tests/Unit/Domains/Checkout/Payment/PayByBankExpirationTest.phpPayByBankExpiration: the 24 h fallback for an unusable PAY_BY_BANK/EXPIRATION value, expiresAt(), and paymentCodeExpiresAt() — the payment-code deadline the job enforces and the REST order resource publishes as pbbExpiresAt
tests/Unit/Helpers/PayWayDebrisCoverageTest.phpDrift guards for the hand-maintained payway lists in ecommercen/helpers/eshop_helper.php (#500, #530, #679, #749), including that every getExternalPayWays() entry is terminable (lands at PENDING_ACCEPTED or is in getCardPayWays())