Appearance
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
statusis notPENDINGandgetDebrisOrders()now selectsstatus(#737); a RESTklarna_paymentsorder Klarna accepts is confirmed toPAIDbefore 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_ticketisvarchar(64)and holds any gateway reference; see decision 737; previous: 2026-11-04 — 4.129.0 resync: the PayByBank expiry cancel now goes throughPayByBankGatewayCancellerand the customer cancel throughPaymentConfirmationService::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.phpandapp.phpcitations 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:
- REST-driven cancellation (
PaymentConfirmationService::cancelPayment()): invoked bycancelByCustomer()for the REST endpointPOST /rest/checkout/cancel-payment/{orderId}and forRest\Order\Controllers\Order(#795, which adds the PayByBank gateway step and can answer 502payment_cancel_failed), and directly by thePollPayByBankStatusjob (the REST webhook family was retired in Advisable-com/ecommercen#721). This is the primary path for REST-placed orders. - Scheduled cleanup (
AdvCancelIncompleteOrderscron): 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 whoseentry_datetimecannot 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 foroperationResult; 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) + ErpHookNote: 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
| File | Role |
|---|---|
ecommercen/job/libraries/AdvCancelIncompleteOrders.php | Job implementation |
application/modules/job/libraries/CancelIncompleteOrders.php | Client-overridable subclass |
application/controllers/Cronjob.php | Deprecated 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.php | getDebrisOrders(), set_status() |
ecommercen/libraries/internal/OrderCancelHookFireTrait.php | ERP cancel hook trait |
ecommercen/libraries/internal/OrderForErpHookFireTrait.php | ERP acceptance hook trait |
src/PaymentGateways/Iris/Iris.php | Iris payment gateway client |
src/PaymentGateways/PayPal/PayPalRestApi.php | PayPal Advanced REST client (getOrderDetails() marks a PayPal 404 with notFound, PayPalRestApi.php:134-138) |
src/PaymentGateways/NexiXPay/XPay.php | Nexi XPay payment gateway client (getOrderStatus, mapOperationResultToStatus) |
ecommercen/gift_cards/jobs/AdvCancelPendingGiftCards.php | Pending gift-card reconciliation (mirrors this flow for gift cards) |
ecommercen/eshop/models/Adv_viva_logging_model.php | Payment logging (modern port: src/Domains/Checkout/VivaLogging/ — #148; legacy model still active) |
ecommercen/coupons/models/Adv_coupons_model.php | Coupon 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 ASCThe 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.
| Gateway | Timeout | Rationale |
|---|---|---|
vivawallet | 2 days (P2D) | Viva Wallet redirects can take longer |
jcc | 20 minutes (PT20M) | Fast redirect flow |
| All others | 3 hours (PT180M) | Standard timeout |
If now > entry_datetime + timeout, delegates to the shared cancelOrder($order) helper, which runs:
set_status(order_serial, 'CANCELED', false, '+', 'order_debris')-- cancels and restores stock (+mode)returnPointsToCustomers()-- rolls back loyalty points ifPOINT_SYSTEM.IS_ENABLEDcancelCoupon()-- marks the applied coupon unused viacoupons_model->markCouponUnused()internalApiOrderCancelHook()-- fires theInternalApiOrderCancelHookfor 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.
entry_datetimeis parsed via the same sharedorderEntryDate()guard described above; anullresult skips the order instead of throwing.- Wait until
entry_datetime + EXPIRATIONhas passed.PayByBankExpiration::secondsFrom()validates the registry value to a positive int before it reaches theDateIntervalspec string, falling back toPayByBankExpiration::DEFAULT_SECONDS = 86400(24 hours; the job'sPAY_BY_BANK_DEFAULT_EXPIRATION_SECONDSis kept as an alias of it) for any unset, empty, non-numeric or non-positive value -- mirroringxPayExpirationSeconds()(Advisable-com/ecommercen#500, #531). The admin field behind this registry key (saved atecommercen/settings/controllers/Adv_settings.php:1446, rendered at:1619, validated at:1722) validates withtrimalone (norequired, nonumeric), 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 invalidDateIntervalspec ('PTS') that would abort the whole cron run. - Call
$this->payByBankGatewayCanceller()->cancel((string) $order->order_serial)(AdvCancelIncompleteOrders.php:154; factory method:424-427, resolved withdi()->get(PayByBankGatewayCanceller::class)). It cancels at PayByBank and returns aPayByBankCancelOutcome(Cancelled,RefusedorUnreachable); the sweep ignores the outcome (#795). - The canceller writes the
pbb_loggingrow (called_for = 'cancel') throughPayByBankLog::recordCancel()(best effort,src/Domains/Checkout/Payment/PayByBankLog.php:16-29). - 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, includingRefusedfor an order the gateway reports paid; the log row records the response).
Iris
Checks actual payment status before deciding:
- Load Iris order record via
order_model->getIrisRecordsByOrderId(). - Call
Iris->getOrderStatus(['orderId' => irisOrderId])to query Iris. - 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, setmeta_datatojob: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:
- Entry-datetime guard:
entry_datetimeis parsed via the sharedorderEntryDate()guard; anullresult skips the order (:225-229). - Grace period: if
now <= entry_datetime + PAYPAL_ADVANCED_GRACE('PT180M',:34, the same 180 minutes ascancelPendingDefaultCards()), return and let the next run retry (:231-233). - No ticket: an empty
tran_ticketmeans PayPal never created the order, so cancel viacancelOrder()(:235-238). - Read the order:
payPalOrderDetails()(:282-287) callsPayPalRestApi->getOrderDetails(tran_ticket). A PayPal 404 comes back asnotFoundand the order is cancelled, because PayPal does not know it (:242-245). Any other failure (timeout, token failure, other HTTP error) has nostatus; it is logged and the order stays PENDING for the next run (:247-256). - Capture statuses: the
statusof every capture in everypurchase_units[].payments.captures[]is collected (:258; the old code looked at the first capture of the first unit only). COMPLETEDcapture 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).- Otherwise: if no capture is
PENDING, cancel viacancelOrder()-- cancel, return points, release the applied coupon, fire cancel hook; aPENDINGcapture 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:
- Entry-datetime guard:
entry_datetimeis parsed via the sharedorderEntryDate()guard described under Default Card Gateways above; anullresult skips the order before the grace-period math below runs. - Grace-period guard (
xPayExpirationSeconds(),ecommercen/job/libraries/AdvCancelIncompleteOrders.php): ifnow <= entry_datetime + XPAY.EXPIRATION seconds, return immediately and let the next 5-minute run retry. The window defaults to10800seconds (180 minutes) and is read from registryXPAY/EXPIRATION; any unset, empty, non-numeric, or non-positive registry value falls back to the default rather than reaching theDateIntervalspec 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/EXPIRATIONis validated the same way bypayByBankExpirationSeconds()(Advisable-com/ecommercen#531) -- see the PayByBank section above. - Call
XPay->getOrderStatus(order_serial)to fetch the Nexi XPay order record - Map
operationResultthroughXPay->mapOperationResultToStatus()to a normalized status - If response is empty or status is not
PAID: cancel via the sharedcancelOrder()helper -- set_status + return points + release coupon + ERP cancel hook - 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 onlycancelByCustomer(...) === PaymentTransition::Appliedas success (:319-322), so a race loser gets 400 "cannot be cancelled in its current status" even though the order isCANCELED; aPaymentCancelFailedExceptionbecomes 502payment_cancel_failed(Order.php:323-333). - PayByBank polling job:
PollPayByBankStatus(src/Domains/Checkout/Jobs/PollPayByBankStatus.php:107-110for orders the gateway no longer knows,:128-131for cancelled gateway statuses).
The method (since #880; the REST-facing contract and race answers are documented in CF-08 Payment Processing):
- Customer path (
cancelByCustomer(),:134-151): for aPENDINGpaybybankorder it first callsPayByBankGatewayCanceller::cancel()outside the database transaction; if the outcome is notCancelledand the order is stillPENDINGit throwsPaymentCancelFailedException(src/Domains/Checkout/Exceptions/PaymentCancelFailedException.php,ERROR_CODE = 'payment_cancel_failed') and the order staysPENDINGwith its stock reserved; otherwise it delegates tocancelPayment()(#795). - Atomic conditional write (
:172-180): insidetransactional(...)it runstransitionStatus($orderId, 'PENDING', 'CANCELED', ...)(:173) and, only if that flip won,$this->stockService->restoreStockForOrder($orderId)(:177) — equivalent to the cron'sset_status('CANCELED', '+')stock-restore path. If the stock release fails the whole cancel rolls back, the order staysPENDINGand aRuntimeExceptionis thrown (:182-184). - Race loser (
:186-192): a call whose flip did not win does nothing and returnsPaymentTransition::AlreadyApplied(the order is alreadyCANCELED) orPaymentTransition::Rejected. - Event dispatch (
:201): only the winner dispatches theOrderCanceledevent, 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. - 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
| Column | Type | Role |
|---|---|---|
id | int | PK |
order_serial | varchar | Human-readable order number |
status | varchar | Current status (filtered for PENDING) |
payway | varchar | Payment gateway identifier |
entry_datetime | datetime | Order creation timestamp (used for timeout) |
coupon_id | int/null | FK to applied coupon |
tran_ticket | varchar(64)/null | Gateway 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_date | datetime | Set on cancellation |
meta_data | text | Audit trail for status changes |
gifts_applied | tinyint(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) |
Related Tables
| Table | Role |
|---|---|
shop_order_basket | Order line items (stock restoration source) |
product_codes | Product SKU stock levels |
iris_orders | Iris payment gateway order mapping |
pbb_logging | PayByBank API call history (database/initial/initial.sql:804; written by PayByBankLog, PayByBankLog.php:11) |
coupons | Coupon usage tracking |
customer_points | Loyalty 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
| Group | Key | Purpose |
|---|---|---|
PAY_BY_BANK | EXPIRATION | Timeout 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) |
XPAY | EXPIRATION | Grace 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_SYSTEM | IS_ENABLED | Whether to rollback loyalty points on cancellation |
Environment / Gateway Configuration
- Iris: configured via
getIrisSettings()helper - PayPal Advanced: configured via
getPaypalAdvancedSettings()helper; thePayPalRestApiclient fetches its access token on first use and bounds every request (15 s total, 3 s connect, constructor defaultsPayPalRestApi.php:31-32) - PayByBank:
PayByBankGatewayCanceller->PayByBankClientFactory::createIfConfigured()(src/Domains/Checkout/Payment/PayByBankClientFactory.php:27-40) - NexiXPay: configured via
getXPaySettings()inecommercen/helpers/registry_helper.php:585-595;XPayclient lazy-instantiated viaxPay()getter; grace period read from registryXPAY/EXPIRATIONviaxPayExpirationSeconds()
Client Extension Points
Override the job class: Extend
AdvCancelIncompleteOrdersinapplication/modules/job/libraries/CancelIncompleteOrders.phpto:- Add custom payment gateway handlers (new
casein the switch) - Change timeout logic for specific gateways
- Add custom notification on cancellation
- If it overrides
getDebrisOrders()(Adv_order_model.php:3444-3454), keepstatusin the select: the loop'sPENDINGskip guard (:65-71) only protects a paid order when the row carriesstatus
- Add custom payment gateway handlers (new
Override
getCardPayWays(): Redefine inapplication/helpers/(the base isfunction_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 howxpay,klarna_payments, andethniki_nbgpaydrifted 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.Custom ERP hooks: The
InternalApiOrderCancelHookandInternalApiOrderForErpHookfire webhooks that ERP integrations can subscribe to for order sync.Adjust schedule: Modify the cron expression and grace time in
jobs.php.
Business Rules
| Rule | Description |
|---|---|
| Card payments only | Only orders with online payment methods (from getCardPayWays()) are considered |
| Gateway-specific timeouts | Viva 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 registry | Timeout 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 registry | Grace period driven by XPAY.EXPIRATION registry value (seconds); no admin UI field, defaults to 180 minutes for any unset/invalid value |
Untrustworthy entry_datetime = skip | An 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 accept | If Iris reports PAID, the order is accepted rather than cancelled |
| Iris PENDING = skip | PENDING Iris orders are retried on the next job run |
| PayPal Advanced acts on PayPal's own answer | After 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 accept | If 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 restored | set_status() with stockMode='+' restores product stock on cancellation; when status === 'CANCELED' it also restores gift stock via restoreOrderGifts() (Advisable-com/ecommercen#688) |
| Coupon released | Applied coupons are marked unused so the customer can reuse them |
| Points returned | Loyalty points are credited back when POINT_SYSTEM.IS_ENABLED |
| ERP notification | Cancel and accept hooks fire for all cancellations/acceptances |
| Idempotent | Only 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:
- Blanket cancel for most payways: gift-card orders older than
giftCardDateTimeIntervalToDropare mass-cancelled viagift_card_orders_model->cancelPending(), except those paid withiris,paypaladvanced, orxpay(:44). - API-verified payways route to dedicated handlers:
cancelPendingIrisOrders()-- usesIris->getOrderStatus()andIrisHelper::interpretIrisResponse()cancelPendingPaypalAdvancedOrders()-- decides only on PayPal's own answer, as the order sweep does (AdvCancelPendingGiftCards.php:227-271, ecommercen#927): an emptytran_ticket(ecommercen#416) or PayPal's 404 cancels; a failed read (nostatus) is logged and the gift card stays pending; aCOMPLETEDcapture on any purchase unit accepts it (PayPalCaptureStatuses::of()); aPENDINGcapture waits; otherwise it is cancelled.payPalOrderDetails()(:279-284) is the test seam.cancelPendingXpayOrders()-- usesXPay->getOrderStatus()andXPay->mapOperationResultToStatus()(:286-311)
- Accept/cancel uses gift-card model methods:
gift_card_orders_model->acceptGiftCard($id)andcancelGiftCard($id)instead ofset_status(). giftCardDateTimeIntervalToDropis now validated the same way the main flow validatesXPAY/PAY_BY_BANKEXPIRATION: the newdateTimeIntervalToDrop()helper guards a missing/empty/non-string config value and a malformedDateIntervalspec, falling back toDEFAULT_DATE_TIME_INTERVAL_TO_DROP = 'PT180M'(3 hours -- identical to the value this repo'sapplication/config/app.php:574ships) and logging at error level (Advisable-com/ecommercen#531). The live vector is a client fork whoseapplication/config/app.phppredates thegiftCardDateTimeIntervalToDropkey: previously,config->item()returningnullfed straight intonew \DateInterval(null), which throws before the job's first query runs, aborting the entire gift-card reconciliation run.
Known Issues & Security Gaps
No grace period for Iris (open): unlike
vivawallet(2 days) and nowxpay(registryXPAY/EXPIRATION, default 180 minutes -- closed for XPay by Advisable-com/ecommercen#500), a PENDINGirisorder 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.xpay/klarna_payments/ethniki_nbgpaypayway-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 sourcegetDebrisOrders()could never select their PENDING orders even though the job's switch already handled them (the gift-card job'sAdvCancelPendingGiftCardsspecial-casedxpaythe whole time, underscoring that it was a registered, live payway). Fixed by adding all three togetCardPayWays(), 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.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-deadxpaybranch -- 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.Observation:
getCardPayWays()andisOrderPaidAtDeliveryByPayWay()'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 partitionallPayWays()along the same PENDING-vs-PENDING_ACCEPTEDlanding-status boundary thatAdv_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.One bad
entry_datetimeaborting the whole cron run -- resolved (Advisable-com/ecommercen#531):cancelPendingDefaultCards(),cancelPendingPayByBank(), andhandlePendingXpayOrders()each fedentry_datetimeintoDateTime::createFromFormat()and called->add()on the result one line later.entry_datetimeisdatetime DEFAULT NULL, soNULL(or an empty/garbage value) is structurally possible; for those,createFromFormat()returnsfalse, andfalse->add()is a fatalErrorin PHP 8 that killed the wholeexecuteCommand()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 returnfalsefor it -- it returns a validDateTimerolled back to-0001-11-30with a "parsed date was invalid" warning fromDateTime::getLastErrors(). Afalse-only guard would have let that object through as valid and silently auto-cancelled the order, since a year-0001timestamp trivially clears every grace window. A related hazard in the same file:cancelPendingPayByBank()interpolated the rawPAY_BY_BANK/EXPIRATIONregistry value into aDateIntervalspec with no validation, so an empty/non-numeric value (reachable via the unvalidatedpay_by_bank_expirationadmin field) built an invalid spec and threw, the same batch-abort. Fixed by the sharedorderEntryDate()guard (which inspectsDateTime::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 bypayByBankExpirationSeconds(), mirroringxPayExpirationSeconds()(#500). The gift-card sibling jobAdvCancelPendingGiftCardshad the analogous hazard aroundgiftCardDateTimeIntervalToDrop, fixed the same way.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 butCOMPLETED, 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).A PayPal capture without a confirmed order needs a human (by design): when the sweep finds a
COMPLETEDcapture 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.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 laterACCEPTEDnotification finds itCANCELED,confirmPayment()returnsRejected, and the handler only logs at error level and answers 200 (src/Domains/Checkout/Payment/KlarnaNotificationHandler.php:108-117).A Klarna confirmation that threw is cancelled by the sweep (open, #1043): if
confirmPayment()throws insidePlaceOrderServiceafter Klarna charged the customer, the order staysPENDINGand no webhook follows for an order Klarna accepted synchronously (PlaceOrderService.php:874-885, logged withlog_message('error', ...)); the sweep cancels it once the timeout passes.
Tests
| Test File | Coverage |
|---|---|
tests/Unit/Jobs/AdvCancelIncompleteOrdersTest.php | Regression 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.php | PayByBankGatewayCanceller::cancel() outcomes (Cancelled, Refused, Unreachable), the paid-status probe and the pbb_logging cancel row (#795) |
tests/Legacy/Eshop/AdvOrderModelBatchCancelPayByBankTest.php | The admin batch cancel (setBatchCanceled()) goes through the canceller (#795) |
tests/Unit/Domains/Checkout/Payment/PayByBankExpirationTest.php | PayByBankExpiration: 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.php | Drift 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()) |
Related Flows
- SY-01 Cron Job Framework -- job scheduling and execution
- AD-03 Order Management -- PENDING to CANCELED transition
- CF-08 Payment Processing -- payment gateway integration
- CF-09 Payment Webhooks -- the Klarna notification arm that confirms a pending-review order before the sweep
- Decision 737 Klarna REST confirmation -- the known Klarna limits of this sweep
- SY-16 PayByBank Polling -- complementary PayByBank status checking