Problem/Motivation
ConditionInterface::evaluate() returns a boolean, so when a condition fails nothing can say why. The most visible case is coupon redemption: CouponRedemption and ManageCouponsForm can only show a generic "coupon not applicable" error, whether the order total is too low, the customer has the wrong role, or the coupon expired.
The coupon error comes from three checks, and only one goes through conditions:
Promotion::applies(): a compatibility check (no other promotion when the promotion is not combinable), then aConditionGroupon the order conditions.Promotion::available(): no conditions at all. Enabled status, coupon requirement, order type, store, start and end dates, usage limit, per-customer usage limit and order email.Coupon::available(): enabled status, the promotion'savailable(), dates, multiple coupons of the same promotion, usage limits.
They are called from PromotionOrderProcessor, CouponRedemption, ManageCouponsForm and CouponValidConstraintValidator.
Order item availability already solved this with a value object: AvailabilityResult (neutral(), unavailable($reason, $code), getReason(), getCode()).
Proposed resolution
One value object, in commerce, returned by all of these: condition plugins' evaluate(), ConditionGroup::evaluate(), Promotion::available(), Promotion::applies() and Coupon::available(). They all answer the same question: can this apply to this order, and if not, why?
Proposed name EvaluationResult (see the naming question below):
EvaluationResult::passed(); EvaluationResult::failed($reason = NULL, $code = NULL); $result->isPassed(); $result->isFailed(); $result->getReason(); // A human-readable, translatable message. $result->getCode(); // A machine-readable code, e.g. for APIs.
The coupon forms then show the reason instead of a generic error.
Codes and reasons (tentative, not settled)
A condition does not know whether its result ends up in front of a customer, an admin or an API client, so the result should not rely on the human-readable reason alone:
- The code is the primary field, scoped by a source so it is unique without a central registry. The plugin returns only a code (documented as a constant on its class);
ConditionGroupstamps the failed condition's plugin ID as the source. Entity checks set their own source (commerce_promotion,commerce_coupon).
class OrderTotalPrice extends ConditionBase { public const MINIMUM_NOT_MET = 'minimum_not_met'; public function evaluate(EntityInterface $entity): EvaluationResult { // ... return EvaluationResult::failed(self::MINIMUM_NOT_MET, $this->t('Your order total is too low for this offer.')); } } // ConditionGroup foreach ($this->conditions as $condition) { $result = $condition->evaluate($entity); if ($result->isFailed()) { return $result->withSource($condition->getPluginId()); } } // Consumer, e.g. the coupon form via Promotion::applies(): if ($result->getSource() === 'order_total_price' && $result->getCode() === OrderTotalPrice::MINIMUM_NOT_MET) { // "Spend X more to use this coupon." }An API client gets
{"source": "commerce_coupon", "code": "expired"}. - The reason is optional and customer-safe by contract: no role names, usage counts or data about other customers. Detailed reasons ("expired" vs "not yet started") also help probing guessed coupon codes, so callers decide what to show: the reason, their own message mapped from the code, or the generic error.
- Alternative: instead of a source string,
ConditionGroupattaches the failed condition itself ($result->getCondition()), which also exposes its configuration (e.g. the minimum amount for a "spend X more" message). Entity-level failures (coupon expired) have no condition, so they still need a code. - Other options considered for codes: a backed enum (typed, but closed to contrib); Symfony-style UUID codes with
getErrorName()(unique, but unreadable in logs and APIs). - Prior art: core's
AccessResultReasonInterface::getReason(), used for debugging and 403 messages rather than end-user copy;AvailabilityResult, whose reason add to cart shows to customers. - Follow-up idea: merchant-configured failure messages per promotion or condition ("Spend $50 more to get free shipping"), the safest option since the merchant writes the copy.
Open questions
- Naming. The name has to read well for conditions, promotions, coupons and other condition consumers (payment gateways, shipping methods). Preferred so far:
EvaluationResult. Options considered:ConditionResult(success()/failure()): natural for conditions, odd onCoupon::available(), which involves no condition.EligibilityResult(eligible()/ineligible()): fits every case; a bit long, and not an existing Commerce term.ApplicabilityResult(applicable()/notApplicable()): matchesapplies(), notavailable(); clumsy.EvaluationResult(passed()/failed()): matchesevaluate(), says nothing about what was evaluated.CheckResult,Verdict,Outcome(pass()/fail()): generic to the point of vague.- Generalize
AvailabilityResult(available()/unavailable()): already exists, but "unavailable" reads oddly for "order total too low", it carries a neutral state, and it lives incommerce_order. ValidationResult: easily confused with Symfony constraints and violations; better avoided.
Other alternatives welcome.
- Relation to
AvailabilityResult: leave it alone, or share a base class? - Combining in
ConditionGroup: with AND, the first failure explains the result; with OR, all conditions failed, so do we return the first failure or all of them? - Audience: reasons are shown to customers (coupon form) and to admins. Some should not leak to customers (usage counts, roles), which may call for a customer-safe reason and a detailed one, or a code that the caller maps to a message.
- BC strategy: changing the return type of
evaluate()breaks every condition plugin, in core (about 20) and in contrib (shipping, payment and tax conditions use the same plugin type). An alternative is a new method with a default implementation inConditionBasethat wraps the booleanevaluate(), so only conditions that want to explain a failure change. The same choice applies toavailable()andapplies(). If the breaking variant is chosen, it must land in 4.0.0. - Other consumers:
PaymentGateway::applies(),TaxType::applies()and shipping methods use conditions and only need the boolean; they keep working viaisPassed().
Remaining tasks
- Settle the open questions above, the name first.
- Implement the value object and convert the core conditions.
- Return it from
Promotion::available(),Promotion::applies()andCoupon::available(), and show the reason in the coupon forms. - Change record.
User interface changes
Coupon redemption shows why a coupon cannot be applied instead of a generic error.
API changes
Depends on the BC strategy: either evaluate(), available() and applies() return the result object (breaking), or new methods are added alongside them.
Data model changes
None.
Comments
Comment #2
jsacksick commentedComment #3
jsacksick commentedComment #4
jsacksick commentedComment #5
jsacksick commentedComment #6
jsacksick commentedProposing an additive approach so this can land in a minor, without breaking BC:
EvaluationResult.ConditionBaseimplements it by wrappingevaluate(), so existing condition plugins (core, shipping, payment, tax, contrib) keep working untouched. Conditions that want to explain failures override the new method and reduceevaluate()toreturn $this->newMethod($entity)->isPassed();.ConditionGroupgets the same new method. With AND, it returns the first failure. Conditions not implementing the new interface get their boolean wrapped.PromotionandCouponget new methods next toapplies()/available(). The existing methods become->isPassed()wrappers, soPromotionOrderProcessorand other callers don't change.CouponRedemption,ManageCouponsFormandCouponValidConstraintValidatorswitch to the new methods and display the reason, falling back to the generic error when there's no reason.Promotion::applies()returns a code-only failure (no reason): it shouldn't surface to the customer by default. Sites can map the code to their own message if they want.This is the main motivation: today there's no way to tell the customer why a coupon doesn't apply, which forces hacks in projects. Exposing
getCode()gives projects a clean way to customize messages.Still open:
ConditionGroupwith OR: return the last failure, or all failures?PaymentGateway::applies(), tax and shipping.