From f6be60e61e91dc12f3ab3aa48f3bd26752a8b1fc Mon Sep 17 00:00:00 2001 From: Wan Zulkarnain Date: Fri, 25 Sep 2026 11:23:52 +0200 Subject: [PATCH] fix: stop sending two emails for one failed renewal A customer received two emails when a renewal failed and the merchant had configured a notification on Subscription Payment Failed: the merchant's notification, and the plugin's built-in dunning email. A failure that exhausted the retry ladder produced two more, because the same moment was announced twice -- as Subscription Payment Failed and again as Subscription Expired. Both were reproduced on a live install before being fixed. One failure with a configured notification produced exactly two messages. The built-in email is a fallback, so it now stands down when Gravity Forms will send a notification for the failure event itself. The stand-down is decided the way core decides it, not by counting configured notifications: - isActive. A notification the merchant switched off is not a replacement. GFCommon::get_notifications() does not filter on isActive, so a check built on that call alone would leave the customer with nothing at all when the merchant had merely parked their own notification. - conditional logic. A notification that cannot fire for this entry is not a replacement either, so the fallback still covers those entries. An operator pressing "Send update-card link" is unaffected: that is a deliberate act by support, not the automated fallback, and it still sends. On the terminal failure only the expiry is announced, and the built-in email is not sent on that path at all. The card-update link stops working the moment the subscription is expired, so an email carrying one would hand the customer a link that is already dead. Customers are dunned on every attempt before that, while action is still possible. Seven sabotage runs, each confirmed to bite before being reverted: removing the stand-down guard; dropping the isActive gate; dropping the conditional-logic gate; matching any event instead of the announced one; announcing both events; deleting the expiry dispatch. The first sabotage run exposed a real gap in the tests -- all six predicate tests passed with the guard removed, because none of them proved anybody called it. That wiring is now covered. --- docs/email-customization.md | 51 ++-- .../class-gf-chip-renewal-notifications.php | 62 +++- includes/class-gf-chip.php | 44 ++- readme.txt | 6 + .../Unit/GF_Chip_RenewalNotificationsTest.php | 277 ++++++++++++++++++ tests/bootstrap.php | 67 +++++ 6 files changed, 470 insertions(+), 37 deletions(-) diff --git a/docs/email-customization.md b/docs/email-customization.md index 3bed321..15a60c7 100644 --- a/docs/email-customization.md +++ b/docs/email-customization.md @@ -4,6 +4,11 @@ Everything here was verified against the plugin's own code and Gravity Forms core. Where a hook is a Gravity Forms hook rather than one of ours, that is stated, so you know who owns it. +Two defects found while writing this are now fixed: the built-in email used to +send unconditionally alongside a configured notification, and a terminal +failure used to announce two events. Both produced two emails for one failed +payment. + ## What already exists (build in the UI, don't code) The plugin gives you a **merge tag**, not an email template: @@ -28,34 +33,38 @@ notification on: So a dunning email with your own design is: one notification, event set to *Subscription Payment Failed*, body containing `{chip_update_card_link}`. -### Read this before configuring that notification +### The built-in email steps aside for yours -The plugin sends a **built-in fallback email** on every failed renewal, and it -does so unconditionally — it does not check whether you have configured a -notification for the event. **Verified on a live install:** with a -*Subscription Payment Failed* notification configured, one failed renewal -produced **two** messages: +The plugin sends a built-in fallback email so dunning works with no setup at +all. When you configure a notification on *Subscription Payment Failed*, the +built-in email **stands down** and yours is the only one the customer receives. -``` -1. to=customer@example.com Action needed: payment failed for your subscription -2. to=probe@example.com the configured notification -``` +The stand-down is decided the way Gravity Forms itself decides whether a +notification will send, so it holds in the cases that catch people out: -So use one or the other: +- a notification you have switched **off** does not suppress the built-in — + otherwise a merchant who parked their notification would leave the customer + with nothing +- a notification whose **conditional logic** will not pass for this entry does + not suppress it either — the fallback exists for the entries nothing else + covers -- Configure the notification and design it, or -- Configure nothing and let the built-in email do the work. +Pressing **Send update-card link** in the admin always sends, regardless. That +is a deliberate act by support, not the automated fallback. -If you need both — a designed customer email and an admin alert on the same -event — put your customer-facing message on the plugin's built-in email and -keep the admin one on a different event. +## The end of the retry ladder -There is a further consequence: a failure that exhausts the retry ladder fires -**both** the failed and the expired event in the same run, so a notification on -each sends twice. Make them distinct messages, not variations of one. +When the last retry fails the subscription is **expired** in the same pass, and +that is the only event announced — *Subscription Expired*. The failure event is +not also fired, so a notification on each will not produce two emails for one +payment. -Both are worth fixing in the plugin — the fallback should stand down when a -notification is configured. Documented here rather than silently worked around. +The built-in email is not sent on that path either. The card-update link stops +working the moment the subscription is expired, so an email carrying one would +hand the customer a link that is already dead. Customers are dunned on every +attempt *before* that, while action is still possible — so make the +*Subscription Expired* notification the one that tells them the subscription +has ended. ## When the customer saves a card on a failed renewal diff --git a/includes/class-gf-chip-renewal-notifications.php b/includes/class-gf-chip-renewal-notifications.php index 8ffa104..ce589ea 100644 --- a/includes/class-gf-chip-renewal-notifications.php +++ b/includes/class-gf-chip-renewal-notifications.php @@ -103,6 +103,53 @@ public static function should_send_dunning( $attempt_index, $last_dunned ) { return (int) $attempt_index > (int) $last_dunned; } + /** + * Whether Gravity Forms will send a notification for this event itself. + * + * The built-in email is a fallback, so it stands down when the merchant has + * built their own — otherwise one failed payment produces two emails. + * + * Mirrors what Gravity Forms does before sending, rather than just counting + * configured notifications. Both gates matter: + * + * - `isActive`. A notification the merchant has switched off is not a + * reason to stay silent. `GFCommon::get_notifications()` does NOT filter + * on this, so reading it and stopping there would send the customer + * nothing at all when the merchant had merely parked their own. + * - conditional logic. A notification that will not pass its conditions + * never sends, so the fallback must still cover that entry. Core's own + * evaluator is called, not a reimplementation: it returns true when a + * notification carries no conditions. + * + * @param string $event The event about to be dispatched. + * @param array $form The form the notification would be read from. + * @param array $entry The entry, for conditional logic. + * @return bool + */ + public static function has_active_notification( $event, $form, $entry ) { + if ( ! is_array( $form ) ) { + return false; + } + + foreach ( (array) rgar( $form, 'notifications' ) as $notification ) { + if ( (string) rgar( $notification, 'event' ) !== (string) $event ) { + continue; + } + + if ( isset( $notification['isActive'] ) && ! $notification['isActive'] ) { + continue; + } + + if ( ! GFCommon::evaluate_conditional_logic( rgar( $notification, 'conditionalLogic' ), $form, $entry ) ) { + continue; + } + + return true; + } + + return false; + } + /** * The subject line for the fallback dunning email. * @@ -307,11 +354,17 @@ private static function strip_tag( $text ) { * that can be updated — emailing a link to a cancelled subscription would * send the customer somewhere that tells them there is nothing to do. * + * Stands down when the merchant has configured a Gravity Forms notification + * that will fire for this event: two emails about one failed payment is + * worse than none, and the merchant's own design wins. The stand-down is + * skipped for an explicit send ($force), because an operator pressing + * "Send update-card link" is asking for this email deliberately. + * * @param int $entry_id Entry id. * @param int $attempt_index Current attempt index. * @param bool $force Send even if already dunned for this attempt. * @param array $extra Optional currency/amount overrides. - * @return bool + * @return bool Whether an email was sent. */ public static function maybe_send_dunning_email( $entry_id, $attempt_index, $force = false, $extra = array() ) { $entry = GFAPI::get_entry( $entry_id ); @@ -326,6 +379,13 @@ public static function maybe_send_dunning_email( $entry_id, $attempt_index, $for return false; } + // The merchant's notification takes priority over the built-in email. + // Checked before a link is issued, so a suppressed send leaves no + // trace behind it either. + if ( ! $force && self::has_active_notification( self::EVENT_FAILED, GFAPI::get_form( rgar( $entry, 'form_id' ) ), $entry ) ) { + return false; + } + $recipient = self::resolve_recipient( $entry ); if ( '' === $recipient ) { diff --git a/includes/class-gf-chip.php b/includes/class-gf-chip.php index 777efa0..575f9e2 100644 --- a/includes/class-gf-chip.php +++ b/includes/class-gf-chip.php @@ -2483,21 +2483,19 @@ private function handle_renewal_failure( $entry, $feed, $purchase, $result, $pla 'error' ); - // Tell the customer. One email per attempt position, so a cron that - // runs twice inside a retry window does not send two identical - // messages. Sent only to the entry's own address. - GF_Chip_Renewal_Notifications::maybe_send_dunning_email( $entry_id, $retry_count ); - - $this->post_payment_action( - $entry, - array( - 'type' => GF_Chip_Renewal_Notifications::EVENT_FAILED, - 'amount' => rgar( $plan, 'amount' ), - 'transaction_id' => $purchase, - 'payment_status' => 'Failed', - ) - ); - + // The ladder is exhausted, so the subscription ends in this same pass. + // + // ONE event is announced here, not two. The failure and the expiry are + // the same moment, and firing both means two emails for one payment -- + // a merchant who configured a notification on each would double-message + // the customer. The expiry is what has actually happened, so it is the + // expiry that gets announced. + // + // The built-in "update your card" email is deliberately not sent on this + // path either. The card-update link stops working the moment the + // subscription is expired, so mailing one here hands the customer a link + // that is already dead by the time they click it. They were dunned on + // every earlier attempt, while action was still possible. if ( null === $next ) { gform_update_meta( $entry_id, 'chip_sub_status', 'expired', $form_id ); gform_update_meta( $entry_id, 'chip_sub_next_payment', '', $form_id ); @@ -2524,6 +2522,22 @@ private function handle_renewal_failure( $entry, $feed, $purchase, $result, $pla ); } + // There are retries left, so the customer still has something to do. + // One email per attempt position, so a cron that runs twice inside a + // retry window does not send two identical messages. Sent only to the + // entry's own address. + GF_Chip_Renewal_Notifications::maybe_send_dunning_email( $entry_id, $retry_count ); + + $this->post_payment_action( + $entry, + array( + 'type' => GF_Chip_Renewal_Notifications::EVENT_FAILED, + 'amount' => rgar( $plan, 'amount' ), + 'transaction_id' => $purchase, + 'payment_status' => 'Failed', + ) + ); + gform_update_meta( $entry_id, 'chip_sub_status', 'on-hold', $form_id ); gform_update_meta( $entry_id, 'chip_sub_next_payment', $next, $form_id ); diff --git a/readme.txt b/readme.txt index ff24e5f..1a899b5 100644 --- a/readme.txt +++ b/readme.txt @@ -211,6 +211,12 @@ In the WordPress admin, open the entry for the subscription under **Forms → En Yes. The plugin adds three notification events you can attach a notification to: **Subscription Renewed**, **Subscription Payment Failed**, and **Subscription Expired**. It also provides the merge tag `{chip_update_card_link}`, which inserts a secure card-update link for that customer. The link is generated fresh each time a notification sends, so a link that has already been used is replaced by a working one. += Will customers get two emails if I write my own dunning notification? = + +No. The plugin sends a built-in dunning email so recovery works with no setup, and that email steps aside as soon as you configure a notification on **Subscription Payment Failed** — yours is then the only one the customer receives. A notification you have switched off, or one whose conditional logic does not pass for that entry, does not count as a replacement: the built-in email still covers those customers. Re-sending the link from the admin always sends, since that is a deliberate action. + +When the retry ladder is exhausted the subscription is marked **Expired** and only that event is announced, so a notification on both **Subscription Payment Failed** and **Subscription Expired** will not double up. The built-in email is not sent at that point either — an update-card link stops working once the subscription is expired, so customers are dunned on the attempts before it instead. + = Are subscription payments refundable? = Subscription charges appear in the entry's payment transactions and can be refunded like any other payment, subject to CHIP's refund policy. Refunds do not cancel the subscription — cancel it separately if you also want charges to stop. diff --git a/tests/Unit/GF_Chip_RenewalNotificationsTest.php b/tests/Unit/GF_Chip_RenewalNotificationsTest.php index 494ca9c..cf6c9bb 100644 --- a/tests/Unit/GF_Chip_RenewalNotificationsTest.php +++ b/tests/Unit/GF_Chip_RenewalNotificationsTest.php @@ -199,6 +199,216 @@ public function test_no_email_for_a_lower_attempt(): void { $this->assertFalse( GF_Chip_Renewal_Notifications::should_send_dunning( 0, 2 ) ); } + // --------------------------------------------------------------------- + // The built-in email is a FALLBACK, not a second opinion. + // --------------------------------------------------------------------- + + /** + * A notification the merchant configured for the failure event suppresses + * the built-in email. + * + * Without this, one failed payment produces two messages: the merchant's + * designed notification AND the built-in fallback. Reproduced on a live + * install before the fix. + */ + public function test_configured_notification_suppresses_the_builtin_email(): void { + $form = array( + 'notifications' => array( + 'merchant' => array( + 'event' => GF_Chip_Renewal_Notifications::EVENT_FAILED, + 'isActive' => true, + ), + ), + ); + + $this->assertTrue( + GF_Chip_Renewal_Notifications::has_active_notification( + GF_Chip_Renewal_Notifications::EVENT_FAILED, + $form, + array() + ) + ); + } + + /** + * A notification for a DIFFERENT event does not suppress it. + * + * The check must be about the event being announced, not about the form + * having notifications at all — otherwise configuring a routine + * admin-submission notification would silence dunning for every customer. + */ + public function test_notification_for_another_event_does_not_suppress(): void { + $form = array( + 'notifications' => array( + 'admin' => array( + 'event' => 'form_submission', + 'isActive' => true, + ), + ), + ); + + $this->assertFalse( + GF_Chip_Renewal_Notifications::has_active_notification( + GF_Chip_Renewal_Notifications::EVENT_FAILED, + $form, + array() + ) + ); + } + + /** + * A notification the merchant switched OFF does not suppress it. + * + * `GFCommon::get_notifications()` does not filter on `isActive`, so a + * check built on that call alone would make the plugin silent for a + * customer whose merchant had merely parked their own notification — + * nobody would be told anything. + */ + public function test_inactive_notification_does_not_suppress(): void { + $form = array( + 'notifications' => array( + 'merchant' => array( + 'event' => GF_Chip_Renewal_Notifications::EVENT_FAILED, + 'isActive' => false, + ), + ), + ); + + $this->assertFalse( + GF_Chip_Renewal_Notifications::has_active_notification( + GF_Chip_Renewal_Notifications::EVENT_FAILED, + $form, + array() + ) + ); + } + + /** + * A notification whose conditional logic will not pass does not suppress it. + * + * The fallback exists so the customer is told when nothing else will. A + * notification that cannot fire for this entry is not "something else". + */ + public function test_unsatisfied_conditional_logic_does_not_suppress(): void { + $form = array( + 'notifications' => array( + 'merchant' => array( + 'event' => GF_Chip_Renewal_Notifications::EVENT_FAILED, + 'isActive' => true, + 'conditionalLogic' => array( + 'logicType' => 'all', + 'rules' => array( + array( + 'fieldId' => '1', + 'operator' => 'is', + 'value' => 'yes', + ), + ), + ), + ), + ), + ); + + $this->assertFalse( + GF_Chip_Renewal_Notifications::has_active_notification( + GF_Chip_Renewal_Notifications::EVENT_FAILED, + $form, + array( '1' => 'no' ) + ) + ); + + // And it DOES suppress the entry it was written for. + $this->assertTrue( + GF_Chip_Renewal_Notifications::has_active_notification( + GF_Chip_Renewal_Notifications::EVENT_FAILED, + $form, + array( '1' => 'yes' ) + ) + ); + } + + /** + * A form with no notifications at all leaves the fallback in charge. + */ + public function test_no_notifications_configured_does_not_suppress(): void { + $this->assertFalse( + GF_Chip_Renewal_Notifications::has_active_notification( + GF_Chip_Renewal_Notifications::EVENT_FAILED, + array(), + array() + ) + ); + + $this->assertFalse( + GF_Chip_Renewal_Notifications::has_active_notification( + GF_Chip_Renewal_Notifications::EVENT_FAILED, + 'not a form', + array() + ) + ); + } + + /** + * The send method actually consults the stand-down before mailing. + * + * The six tests above prove the predicate is correct; none of them proves + * anybody calls it. Removing the guard from `maybe_send_dunning_email()` + * left the whole suite green — which is exactly the double-send bug, + * restored. This test is the wiring, and it must fail if the guard goes. + */ + public function test_the_send_consults_the_stand_down_before_mailing(): void { + $source = file_get_contents( __DIR__ . '/../../includes/class-gf-chip-renewal-notifications.php' ); + $source = str_replace( "\r\n", "\n", $source ); + + $start = strpos( $source, 'public static function maybe_send_dunning_email' ); + $this->assertNotFalse( $start, 'the send method must exist' ); + + $body = substr( $source, $start, 3000 ); + + $guard = strpos( $body, 'has_active_notification' ); + $mail = strpos( $body, 'wp_mail(' ); + + $this->assertNotFalse( $guard, 'the send must consult the merchant notification stand-down' ); + $this->assertNotFalse( $mail, 'the send must still mail' ); + + $this->assertLessThan( + $mail, + $guard, + 'the stand-down must be decided BEFORE wp_mail, or the email has already left' + ); + + $this->assertStringContainsString( + 'self::EVENT_FAILED', + $body, + 'the stand-down must ask about the failure event, which is the one the fallback covers' + ); + } + + /** + * An operator's explicit send ignores the stand-down. + * + * "Send update-card link" is a deliberate act by support, not the automated + * fallback. Suppressing it because the merchant happens to run their own + * notification would make the button appear broken. + */ + public function test_an_explicit_send_is_not_suppressed(): void { + $source = file_get_contents( __DIR__ . '/../../includes/class-gf-chip-renewal-notifications.php' ); + $source = str_replace( "\r\n", "\n", $source ); + + $start = strpos( $source, 'public static function maybe_send_dunning_email' ); + $body = substr( $source, $start, 3000 ); + + $guard_line = strpos( $body, 'has_active_notification' ); + $line_start = strrpos( substr( $body, 0, $guard_line ), "\n" ); + $guard_stmt = substr( $body, $line_start, 400 ); + + $this->assertStringContainsString( + '! $force', + $guard_stmt, + 'the stand-down must be bypassed for an operator-initiated send' + ); + } + // --------------------------------------------------------------------- // Email content. // --------------------------------------------------------------------- @@ -600,6 +810,73 @@ public function test_failure_path_invokes_dunning(): void { ); } + /** + * The dunning email is attempted ONLY while retries remain, and a terminal + * failure announces ONE event rather than two. + * + * The failure and the expiry are the same moment, so firing both meant a + * merchant with a notification on each got two emails for one payment. + * The built-in "update your card" email is deliberately skipped on that + * path as well: the card-update link stops working the moment the + * subscription is expired, so mailing one would hand the customer a dead + * link. They were dunned on every earlier attempt, while action was still + * possible. + * + * Anchored on the marker comment rather than on `if ( null === $next )`, + * which appears twice in this method and would match the log_debug guard. + */ + public function test_terminal_failure_announces_the_expiry_only(): void { + $source = file_get_contents( __DIR__ . '/../../includes/class-gf-chip.php' ); + $source = str_replace( "\r\n", "\n", $source ); + + $start = strpos( $source, 'private function handle_renewal_failure' ); + $this->assertNotFalse( $start, 'handle_renewal_failure must exist' ); + + $body = substr( $source, $start, 8000 ); + + $exhausted_at = strpos( $body, 'The ladder is exhausted' ); + $this->assertNotFalse( $exhausted_at, 'the exhausted branch must be marked' ); + + $send_at = strpos( $body, 'maybe_send_dunning_email( $entry_id, $retry_count )' ); + $this->assertNotFalse( $send_at, 'the dunning send must exist' ); + + $this->assertLessThan( + $send_at, + $exhausted_at, + 'the terminal branch must be handled before the dunning send, so the send cannot run on it' + ); + + $exhausted = substr( $body, $exhausted_at, $send_at - $exhausted_at ); + + $this->assertStringContainsString( + 'GF_Chip_Renewal_Notifications::EVENT_EXPIRED', + $exhausted, + 'a terminal failure must announce the expiry' + ); + + $this->assertStringNotContainsString( + 'GF_Chip_Renewal_Notifications::EVENT_FAILED', + $exhausted, + 'a terminal failure must not ALSO announce the failure — that is one email too many' + ); + + $this->assertStringNotContainsString( + 'maybe_send_dunning_email', + $exhausted, + 'the built-in email must not be sent once the ladder is exhausted — the link is already dead' + ); + + // The retry path still does both, so the guards above cannot be + // satisfied by deleting the work instead of gating it. + $retry_path = substr( $body, $send_at ); + + $this->assertStringContainsString( + 'GF_Chip_Renewal_Notifications::EVENT_FAILED', + $retry_path, + 'a non-terminal failure must still announce the failure event' + ); + } + /** * The success path dispatches the renewed event. */ diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 3c31c3a..9d2a2cd 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -759,6 +759,73 @@ public static function current_user_can_any( $caps ) { return current_user_can( 'gform_full_access' ); } + + /** + * Evaluates a conditional-logic block. + * + * The plugin calls this to decide whether a merchant's notification + * will actually fire. Core returns TRUE for a block with no rules, and + * that is the behaviour that matters most here: a notification with no + * conditions is one that WILL send, so the built-in email must stand + * down. A stub that defaulted to false would report the opposite and + * let the double-send back in. + * + * The operators below cover what a notification's conditional logic + * realistically uses; anything unrecognised evaluates false, matching + * core's own default of "the rule did not match". + * + * @param array $logic Conditional logic block. + * @param array $form Form. + * @param array $entry Entry. + * @return bool + */ + public static function evaluate_conditional_logic( $logic, $form = null, $entry = null ) { + $rules = rgar( $logic, 'rules' ); + + if ( empty( $rules ) || ! is_array( $rules ) ) { + return true; + } + + $matched = 0; + + foreach ( $rules as $rule ) { + $field = (string) rgar( $rule, 'fieldId' ); + $actual = isset( $entry[ $field ] ) ? $entry[ $field ] : null; + + if ( ! self::hermes_rule_matches( rgar( $rule, 'operator' ), $actual, rgar( $rule, 'value' ) ) ) { + continue; + } + + ++$matched; + } + + return 'any' === rgar( $logic, 'logicType' ) ? $matched > 0 : $matched === count( $rules ); + } + + /** + * Whether one conditional-logic rule matches. + * + * @param string $operator Operator. + * @param mixed $actual Value from the entry. + * @param mixed $expected Value from the rule. + * @return bool + */ + private static function hermes_rule_matches( $operator, $actual, $expected ) { + switch ( (string) $operator ) { + case 'is': + return (string) $actual === (string) $expected; + case 'isnot': + return (string) $actual !== (string) $expected; + case '>': + return (float) $actual > (float) $expected; + case '<': + return (float) $actual < (float) $expected; + case 'contains': + return false !== strpos( (string) $actual, (string) $expected ); + default: + return false; + } + } } }