diff --git a/README.md b/README.md
index f2d7f85..f7b75b2 100644
--- a/README.md
+++ b/README.md
@@ -74,6 +74,13 @@ server sees.
## Privacy and moderation
- Donors choose a name or "Anonymous". For anonymous donors the **name is never stored**.
- Optional message approval queue and a streamer-controlled profanity filter (whole-word, your own word list).
+- The filter masks bad words in messages and in donor names (anonymous donors have no stored name). If a **donor name**
+ trips the filter, the donation still completes and counts towards the goal, timer, counters, rewards and tiers, but it
+ is **held on the Moderation screen** (flagged "Name", "Message" or "Name and message") even when message moderation is
+ off. A held donation shows no alert (name or message) and no public donor-feed entry until you approve it; approving
+ shows the already-masked name. Rejecting it means it is never shown.
+- If the server dies right after a payment is recorded, a five-minute background job re-applies any timer, counter,
+ reward and tier effects that were missed (never twice).
## Not supported
- **Refunds and chargebacks are not tracked.** Refunds and chargebacks done in PayPal are NOT reflected in goal
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 14e0303..a53e694 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -20,7 +20,7 @@ Namespace `StreamGoals\`, PSR-4 rooted at `includes/`. Text domain `streamgoals-
## Database (created by `Core\Installer`, version in option `sg_db_version`)
- `sg_goals`: id, title, target_minor, currency, status(active|paused|complete), starts_at, ends_at NULL, counts_fees TINYINT(0 = base amount only), created_at
-- `sg_donations`: id, goal_id, paypal_order_id, paypal_capture_id UNIQUE, base_minor, fee_minor, total_minor, currency, donor_name, is_anonymous, message, status(pending|completed|refunded|reversed), moderation(approved|pending|rejected), created_at
+- `sg_donations`: id, goal_id, paypal_order_id, paypal_capture_id UNIQUE, base_minor, fee_minor, total_minor, currency, donor_name, is_anonymous, message, status(pending|completed|refunded|reversed), moderation(approved|pending|rejected), moderation_flags, effects_applied_at NULL (v6), created_at
- `sg_rules`: id, goal_id, type(add_time|counter|bonus), config JSON, enabled, sort
- `sg_rule_events`: id, rule_id, donation_id, delta (seconds or count), reversed TINYINT, created_at — UNIQUE(rule_id, donation_id) for idempotency
- `sg_state`: goal_id, key, value — timer `ends_at`, counter totals, carry-over remainders
@@ -92,3 +92,17 @@ A goal may have ordered TIERS; each is a cumulative target with an item/unlock (
- "Current tier" = the first tier (by target) with reached_at IS NULL. Goal bar progress for a tiered goal = (raised - floor) / (target - floor) clamped 0..1, where floor = previous tier's target (0 for the first); the cumulative raised and the current tier target are still displayed.
- Reached tiers: title/description editable, target locked; a new tier's target must be above the goal's current raised total and unique.
- Overlay `goal` payload for a tiered goal adds `tiers: {count, index (1-based current), current:{title,description,target_minor,target_display,floor_minor}|null, all_reached}`; untiered goals are unchanged. Alert payloads gain `tiers: [{title}]` = tiers whose reached_donation_id is that donation, shown as a "TIER UNLOCKED: title" pill.
+
+## Schema v6 (Installer, DB_VERSION 6): donor-name flagging + effects reconciliation
+Only our own `sg_donations` table changes (two columns, added by dbDelta):
+- `moderation_flags VARCHAR(16) NOT NULL DEFAULT ''`: why a row is held. `''` (legacy/approved), `message`, `name` or `name,message`. Display only (`Admin\Format::flaggedLabel`); `moderation` stays the single source of truth for visibility. A held row with `''` flags is shown as "Message" (before v6 only messages were held).
+- `effects_applied_at DATETIME NULL`: set (UTC) once ALL side effects of a completed donation finished without error.
+
+### Donor-name flagging
+`OrderValidator::validate` runs the streamer's `ProfanityFilter` over `donor_name` (non-anonymous only; anonymous names are blanked first and never stored). `ProfanityFilter::matches()` shares the scan with `filter()`. The filter has a single mode, MASK: the stored name is already masked (`f***`), exactly like messages. A tripped name sets `moderation='pending'` and `moderation_flags` includes `name`, independent of the `moderate_messages` setting; a non-empty message with `moderate_messages` on adds `message`. The donation completes and counts for goal/timer/counter/rewards/tiers as usual (moderation never gates those).
+Alerts: `Overlay\Payloads::alerts` (and `WpdbDataSource`, `DonationRepository::recentApproved`) only emit `completed` + `approved` rows, so a held donation emits NO alert at all (the whole alert is held, same as a held message). It is never shown as "Anonymous". After Approve the alert shows the masked name; Reject = never shown.
+
+### Reconciliation of "completed but side effects lost"
+`DonationStore::notify_applied($id): bool` runs engine (rules/timer/counter), `Actions\Recorder`, `Tiers\Recorder` (before the close check), then end-at-target, and only if every step succeeded calls `mark_effects_applied` (`UPDATE ... WHERE effects_applied_at IS NULL`). `CaptureFinalizer` is unchanged: `mark_completed` stays the atomic single-winner pending->completed step and both the capture endpoint and the webhook call `notify_applied` only for the winner, so a replay never re-runs it inline.
+`Maintenance::reconcile_effects` (cron `sg_reconcile_effects`, every 5 min, single-flight via `GET_LOCK`) selects up to 25 `status='completed' AND effects_applied_at IS NULL AND goal_id>0` rows created more than 2 minutes and less than 30 days ago and calls `notify_applied` again. Replay safety: rules via `sg_rule_events` UNIQUE(rule_id,donation_id) (event inserted first, state only touched if new, under the goal lock); rewards via `INSERT IGNORE` on UNIQUE(donation_id,action_id); tiers via `UPDATE ... WHERE reached_at IS NULL`; close-at-target via `UPDATE ... WHERE status='active'`.
+Upgrade: `Installer::maybe_upgrade` passes the stored version to `install_schema`; when it is < 6 (or absent) it backfills `effects_applied_at` for every already-completed row BEFORE writing `sg_db_version`, so history is never replayed and a failed backfill is retried on the next load. Known gap (unchanged): in `Engine::applyRule` the event row is recorded before state is updated, so a death between those two statements loses that single rule's effect and a replay skips it.
diff --git a/includes/Actions/Recorder.php b/includes/Actions/Recorder.php
index fd3e2cd..f7c0031 100644
--- a/includes/Actions/Recorder.php
+++ b/includes/Actions/Recorder.php
@@ -6,21 +6,27 @@ namespace StreamGoals\Actions;
/** Queues the on-stream actions a completed donation triggers. */
final class Recorder {
- /** Never throws. Idempotent: replays are ignored by the UNIQUE key on sg_action_events. */
- public static function forDonation( int $donationId ): void {
+ /**
+ * Never throws. Idempotent: replays are ignored by the UNIQUE key on sg_action_events.
+ *
+ * @return bool False only when something failed (so the caller must not mark the donation's effects as applied).
+ */
+ public static function forDonation( int $donationId ): bool {
try {
global $wpdb;
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, base_minor, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
if ( ! is_array( $row ) || 'completed' !== ( $row['status'] ?? '' ) ) {
- return;
+ return true;
}
$repo = new ActionRepository( $wpdb );
$matches = Matcher::match( (int) $row['base_minor'], $repo->enabledForGoal( (int) $row['goal_id'] ) );
if ( $matches ) {
$repo->recordEvents( $donationId, $matches );
}
+ return true;
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: Recorder failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
+ return false;
}
}
}
diff --git a/includes/Admin/DonationsPage.php b/includes/Admin/DonationsPage.php
index 6ffb350..12066b0 100644
--- a/includes/Admin/DonationsPage.php
+++ b/includes/Admin/DonationsPage.php
@@ -52,7 +52,7 @@ final class DonationsPage {
echo Admin::td( 'Donor' ) . esc_html( Format::donorName( $r ) ) . ( $test ? ' TEST' : '' ) . '';
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '' . Admin::td( 'Fee' ) . esc_html( Format::money( (int) $r['fee_minor'], $cur ) ) . '' . Admin::td( 'Total paid' ) . esc_html( Format::money( (int) $r['total_minor'], $cur ) ) . '';
echo Admin::td( 'Goal' ) . esc_html( $test ? '(test)' : ( $goals[ (int) $r['goal_id'] ] ?? '#' . (int) $r['goal_id'] ) ) . '';
- echo Admin::td( 'Status' ) . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' message ' . esc_html( (string) $r['moderation'] ) . '' ) . '';
+ echo Admin::td( 'Status' ) . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' ' . esc_html( strtolower( Format::flaggedLabel( $r ) ) . ' ' . (string) $r['moderation'] ) . '' ) . '';
echo Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '';
}
echo Admin::tableClose();
@@ -72,22 +72,22 @@ final class DonationsPage {
}
public static function renderModeration(): void {
- Admin::open( 'Message moderation' );
+ Admin::open( 'Moderation' );
if ( ! Settings::get( 'moderate_messages' ) ) {
- echo '
Message moderation is currently off in Settings, so new messages are shown without review. Anything still waiting below was submitted while it was on.
';
+ echo '
Message moderation is currently off in Settings, so new messages are shown without review. A donor name that trips the profanity filter is still held here, and anything else waiting below was submitted earlier.
';
}
- echo '
Approved messages can appear in alerts. Rejected messages are hidden. The donation itself still counts towards your goal either way.
';
+ echo '
Held donations stay out of alerts (and the public donor feed) until you approve them. Rejected ones are never shown. A donor name that trips the profanity filter is held here too; it is already masked (for example f***), and approving shows it masked. The donation itself still counts towards your goal, timer and counters either way.
A donor name that trips the filter is masked and the donation is held on the Moderation screen before its alert can show (it still counts towards your goal). ';
echo '';
echo '
';
diff --git a/includes/Core/DonationRepository.php b/includes/Core/DonationRepository.php
index 3d1a898..481c563 100644
--- a/includes/Core/DonationRepository.php
+++ b/includes/Core/DonationRepository.php
@@ -22,7 +22,7 @@ final class DonationRepository {
/** @return int|null new id, or null on failure (e.g. duplicate capture id). */
public function insert( array $d ): ?int {
- $allowed = array( 'goal_id', 'paypal_order_id', 'paypal_capture_id', 'base_minor', 'fee_minor', 'total_minor', 'currency', 'donor_name', 'is_anonymous', 'message', 'status', 'moderation' );
+ $allowed = array( 'goal_id', 'paypal_order_id', 'paypal_capture_id', 'base_minor', 'fee_minor', 'total_minor', 'currency', 'donor_name', 'is_anonymous', 'message', 'status', 'moderation', 'moderation_flags' );
$row = array_intersect_key( $d, array_flip( $allowed ) );
$row += array( 'status' => 'pending', 'moderation' => 'approved', 'fee_minor' => 0 );
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
diff --git a/includes/Core/Installer.php b/includes/Core/Installer.php
index 88466c1..925b0f0 100644
--- a/includes/Core/Installer.php
+++ b/includes/Core/Installer.php
@@ -8,10 +8,10 @@ namespace StreamGoals\Core;
*/
final class Installer {
- public const DB_VERSION = '5';
+ public const DB_VERSION = '6';
public static function activate(): void {
- self::install_schema();
+ self::install_schema( get_option( 'sg_db_version' ) );
if ( false === get_option( 'sg_settings' ) ) {
add_option( 'sg_settings', Settings::defaults(), '', false );
}
@@ -20,12 +20,33 @@ final class Installer {
/** Run on plugins_loaded so upgrades apply without re-activation. */
public static function maybe_upgrade(): void {
- if ( get_option( 'sg_db_version' ) !== self::DB_VERSION ) {
- self::install_schema();
+ $from = get_option( 'sg_db_version' );
+ if ( $from !== self::DB_VERSION ) {
+ self::install_schema( $from );
}
}
- private static function install_schema(): void {
+ /** Schema v6 added sg_donations.effects_applied_at; rows completed before that must not be replayed. */
+ public static function needsEffectsBackfill( mixed $from ): bool {
+ return false === $from || '' === $from || version_compare( (string) $from, '6', '<' );
+ }
+
+ /**
+ * One-time upgrade step: every donation that is ALREADY completed had its side effects applied by the code that
+ * completed it (or was lost before this feature existed and is not worth replaying), so stamp it. Without this the
+ * reconciler would replay the whole history. Only touches NULL rows, so re-running is harmless. False on DB error.
+ */
+ public static function backfill_effects_applied(): bool {
+ global $wpdb;
+ $n = $wpdb->query( $wpdb->prepare(
+ 'UPDATE ' . $wpdb->prefix . "sg_donations SET effects_applied_at = %s WHERE status = 'completed' AND effects_applied_at IS NULL",
+ gmdate( 'Y-m-d H:i:s' )
+ ) );
+ return false !== $n;
+ }
+
+ /** @param mixed $from Previously installed sg_db_version (false when never installed). */
+ private static function install_schema( mixed $from = false ): void {
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$c = $wpdb->get_charset_collate();
@@ -59,6 +80,8 @@ final class Installer {
message VARCHAR(500) NOT NULL DEFAULT '',
status VARCHAR(12) NOT NULL DEFAULT 'pending',
moderation VARCHAR(10) NOT NULL DEFAULT 'approved',
+ moderation_flags VARCHAR(16) NOT NULL DEFAULT '',
+ effects_applied_at DATETIME NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY capture (paypal_capture_id),
@@ -159,6 +182,11 @@ final class Installer {
KEY reached_donation (reached_donation_id)
) $c;" );
+ // Backfill BEFORE recording the new version: if it fails, the next load retries instead of replaying history.
+ if ( self::needsEffectsBackfill( $from ) && ! self::backfill_effects_applied() ) {
+ return;
+ }
+
update_option( 'sg_db_version', self::DB_VERSION );
}
}
diff --git a/includes/Core/Maintenance.php b/includes/Core/Maintenance.php
index 2eb1fe5..a75fad8 100644
--- a/includes/Core/Maintenance.php
+++ b/includes/Core/Maintenance.php
@@ -14,15 +14,87 @@ final class Maintenance {
public const HOOK = 'sg_purge_abandoned';
public const MAX_AGE_DAYS = 7;
+ /** Reconcile "completed but side effects lost" donations (see reconcile_effects()). */
+ public const RECONCILE_HOOK = 'sg_reconcile_effects';
+ public const RECONCILE_SCHEDULE = 'sg_five_minutes';
+ /** A donation must be this old before it is replayed, so a request still applying its effects is left alone. */
+ public const RECONCILE_MIN_AGE = 120;
+ /** Older donations are not retried (a row that can never succeed must not be replayed forever). */
+ public const RECONCILE_MAX_AGE_DAYS = 30;
+ public const RECONCILE_BATCH = 25;
+
public static function register(): void {
add_action( self::HOOK, array( self::class, 'purge_abandoned' ) );
if ( ! wp_next_scheduled( self::HOOK ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK );
}
+ add_filter( 'cron_schedules', array( self::class, 'cron_schedules' ) );
+ add_action( self::RECONCILE_HOOK, array( self::class, 'reconcile_effects' ) );
+ if ( ! wp_next_scheduled( self::RECONCILE_HOOK ) ) {
+ wp_schedule_event( time() + 300, self::RECONCILE_SCHEDULE, self::RECONCILE_HOOK );
+ }
+ }
+
+ /** @param array $schedules @return array */
+ public static function cron_schedules( $schedules ): array {
+ $schedules = is_array( $schedules ) ? $schedules : array();
+ $schedules[ self::RECONCILE_SCHEDULE ] = array( 'interval' => 300, 'display' => 'Every five minutes (StreamGoals)' );
+ return $schedules;
}
public static function unschedule(): void {
wp_clear_scheduled_hook( self::HOOK );
+ wp_clear_scheduled_hook( self::RECONCILE_HOOK );
+ }
+
+ /**
+ * Replays the side effects (rules/timer/counter, rewards, tiers, end-at-target) of completed donations whose request
+ * died before DonationStore::notify_applied() could stamp effects_applied_at. Safe by construction: every effect is
+ * idempotent per (rule, donation) / (donation, action) / tier, and the donation row itself is never touched here.
+ * Single-flight through a MySQL named lock so overlapping cron runs do not pile up.
+ *
+ * @return int Donations whose effects were confirmed applied by this run.
+ */
+ public static function reconcile_effects(): int {
+ global $wpdb;
+ $locked = $wpdb && 1 === (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', 'sg_reconcile_effects' ) );
+ if ( ! $locked ) {
+ return 0;
+ }
+ try {
+ return self::reconcile(
+ time(),
+ array( \StreamGoals\PayPal\DonationStore::class, 'unapplied_completed_ids' ),
+ array( \StreamGoals\PayPal\DonationStore::class, 'notify_applied' )
+ );
+ } catch ( \Throwable $e ) {
+ error_log( 'StreamGoals: reconcile failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
+ return 0;
+ } finally {
+ $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', 'sg_reconcile_effects' ) );
+ }
+ }
+
+ /**
+ * Pure orchestration (unit-tested).
+ *
+ * @param callable $find fn(string $notAfter, string $notBefore, int $limit): int[]
+ * @param callable $apply fn(int $donationId): bool true once the donation is stamped as applied
+ */
+ public static function reconcile( int $now, callable $find, callable $apply ): int {
+ $notAfter = gmdate( 'Y-m-d H:i:s', $now - self::RECONCILE_MIN_AGE );
+ $notBefore = gmdate( 'Y-m-d H:i:s', $now - self::RECONCILE_MAX_AGE_DAYS * 86400 );
+ $done = 0;
+ foreach ( (array) $find( $notAfter, $notBefore, self::RECONCILE_BATCH ) as $id ) {
+ try {
+ if ( $apply( (int) $id ) ) {
+ ++$done;
+ }
+ } catch ( \Throwable $e ) {
+ error_log( 'StreamGoals: reconcile of donation ' . (int) $id . ' failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
+ }
+ }
+ return $done;
}
/**
diff --git a/includes/Core/ProfanityFilter.php b/includes/Core/ProfanityFilter.php
index 4d0d05d..28af24b 100644
--- a/includes/Core/ProfanityFilter.php
+++ b/includes/Core/ProfanityFilter.php
@@ -58,8 +58,23 @@ final class ProfanityFilter {
return $this->enabled && array() !== $this->words;
}
+ /**
+ * True when at least one word of $text is listed, i.e. filter() would change it. Same rules as filter()
+ * (whole words, leetspeak, case-insensitive). Used to hold a donor name for moderation. Never throws.
+ */
+ public function matches( string $text ): bool {
+ $hit = false;
+ $this->scan( $text, $hit );
+ return $hit;
+ }
+
/** Mask every listed word; everything else is returned byte-for-byte (after UTF-8 scrubbing). */
public function filter( string $text ): string {
+ $hit = false;
+ return $this->scan( $text, $hit );
+ }
+
+ private function scan( string $text, bool &$hit ): string {
if ( ! $this->isEnabled() || '' === $text ) {
return $text;
}
@@ -70,13 +85,14 @@ final class ProfanityFilter {
$text = mb_scrub( $text, 'UTF-8' );
$out = preg_replace_callback(
'/[\p{L}\p{M}\p{N}@$!]+/u',
- function ( array $m ): string {
+ function ( array $m ) use ( &$hit ): string {
$tok = $m[0];
// "!" is only a leet char inside a word; trailing/leading punctuation is not part of it.
$core = trim( $tok, '!' );
if ( '' === $core || ! $this->isListed( $core ) ) {
return $tok;
}
+ $hit = true;
$lead = (int) strspn( $tok, '!' );
$trail = strlen( $tok ) - strlen( rtrim( $tok, '!' ) );
return str_repeat( '!', $lead ) . str_repeat( '*', mb_strlen( $core ) ) . str_repeat( '!', $trail );
diff --git a/includes/Core/Uninstaller.php b/includes/Core/Uninstaller.php
index 7292ffb..01c0513 100644
--- a/includes/Core/Uninstaller.php
+++ b/includes/Core/Uninstaller.php
@@ -82,6 +82,7 @@ final class Uninstaller {
public static function run_site( object $wpdb ): void {
$delete = self::wants_data_deleted( get_option( 'sg_settings', array() ) );
wp_clear_scheduled_hook( self::CRON_HOOK );
+ wp_clear_scheduled_hook( Maintenance::RECONCILE_HOOK );
self::delete_dynamic_transients( $wpdb );
if ( $delete ) {
self::drop_tables( $wpdb );
diff --git a/includes/PayPal/DonationStore.php b/includes/PayPal/DonationStore.php
index 690b000..69a6d37 100644
--- a/includes/PayPal/DonationStore.php
+++ b/includes/PayPal/DonationStore.php
@@ -60,9 +60,10 @@ final class DonationStore {
'message' => $v['message'],
'status' => 'pending',
'moderation' => $v['moderation'],
+ 'moderation_flags' => (string) ( $v['moderation_flags'] ?? '' ),
'created_at' => gmdate( 'Y-m-d H:i:s' ),
),
- array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s' )
+ array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s' )
);
return $ok ? (int) $wpdb->insert_id : 0;
}
@@ -98,37 +99,71 @@ final class DonationStore {
return 1 === $n;
}
- /** Hand a freshly completed donation to the rules engine (if present). Never throws. */
- public static function notify_applied( int $id ): void {
- self::call_engine( 'applyDonation', $id );
+ /**
+ * Run every side effect of a completed donation (rules/timer/counter, rewards, tiers, end-at-target) and, only if ALL of
+ * them finished without error, stamp sg_donations.effects_applied_at. Never throws. Every step is idempotent, so this is
+ * also what Maintenance::reconcile_effects() replays for a donation whose request died after mark_completed().
+ *
+ * @return bool True when the donation is (now) marked as fully applied.
+ */
+ public static function notify_applied( int $id ): bool {
+ $ok = self::call_engine( 'applyDonation', $id );
// Donation actions (rewards). Not under the goal lock: events are idempotent via a UNIQUE key. Never throws.
- try {
- \StreamGoals\Actions\Recorder::forDonation( $id );
- } catch ( \Throwable $e ) {
- error_log( 'StreamGoals: Recorder failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
+ if ( ! \StreamGoals\Actions\Recorder::forDonation( $id ) ) {
+ $ok = false;
}
// Goal tiers: unlock every tier this donation reaches. MUST run before the close-at-target check below
// (the final tier's target is the goal target). Own try/catch; never throws, never delays a capture.
- try {
- \StreamGoals\Tiers\Recorder::forDonation( $id );
- } catch ( \Throwable $e ) {
- error_log( 'StreamGoals: tier unlock failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
+ if ( null === \StreamGoals\Tiers\Recorder::forDonationChecked( $id ) ) {
+ $ok = false;
}
- self::close_goal_if_target_reached( $id );
+ if ( ! self::close_goal_if_target_reached( $id ) ) {
+ $ok = false;
+ }
+ return $ok && self::mark_effects_applied( $id );
+ }
+
+ /** Stamp "side effects applied" once. Only a completed row with a NULL stamp is touched (first stamp wins). */
+ public static function mark_effects_applied( int $id ): bool {
+ global $wpdb;
+ $n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET effects_applied_at = %s WHERE id = %d AND status = 'completed' AND effects_applied_at IS NULL", gmdate( 'Y-m-d H:i:s' ), $id ) );
+ return false !== $n;
+ }
+
+ /**
+ * Completed donations whose side effects were never confirmed: completed, effects_applied_at NULL, a real goal
+ * (test rows use goal_id 0), created between $notBefore and $notAfter (UTC 'Y-m-d H:i:s'; the lower bound keeps a
+ * permanently failing row from being retried forever, the upper bound leaves in-flight requests alone). Oldest first.
+ *
+ * @return int[]
+ */
+ public static function unapplied_completed_ids( string $notAfter, string $notBefore, int $limit ): array {
+ global $wpdb;
+ $ids = $wpdb->get_col( $wpdb->prepare(
+ 'SELECT id FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND effects_applied_at IS NULL AND goal_id > 0 AND created_at < %s AND created_at >= %s ORDER BY id ASC LIMIT %d",
+ $notAfter,
+ $notBefore,
+ max( 1, $limit )
+ ) );
+ return array_map( 'intval', (array) $ids );
}
/**
* "End at target": runs after the donation is already completed and counted, so it can never refuse or
* undo a capture. Failures are logged and swallowed. Idempotent (atomic UPDATE ... WHERE status='active').
+ *
+ * @return bool False when the check failed.
*/
- public static function close_goal_if_target_reached( int $donationId ): void {
+ public static function close_goal_if_target_reached( int $donationId ): bool {
try {
$row = self::find( $donationId );
if ( $row && (int) $row->goal_id > 0 ) {
( new \StreamGoals\Core\GoalRepository() )->closeIfTargetReached( (int) $row->goal_id );
}
+ return true;
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: end-at-target check failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
+ return false;
}
}
@@ -138,10 +173,10 @@ final class DonationStore {
return (array) $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'complete' AND close_at_target = 1 ORDER BY id DESC LIMIT 20", ARRAY_A );
}
- private static function call_engine( string $method, int $id ): void {
+ private static function call_engine( string $method, int $id ): bool {
$row = self::find( $id );
if ( ! $row ) {
- return;
+ return false; // vanished row: nothing to apply, and never claim success
}
try {
$donation = \StreamGoals\Core\DonationRepository::toDonation( (array) $row );
@@ -151,8 +186,10 @@ final class DonationStore {
\StreamGoals\Rules\Engine::default()->$method( $donation );
}
);
+ return true;
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: Engine::' . $method . ' failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
+ return false;
}
}
}
diff --git a/includes/PayPal/OrderValidator.php b/includes/PayPal/OrderValidator.php
index 0b224c4..8410690 100644
--- a/includes/PayPal/OrderValidator.php
+++ b/includes/PayPal/OrderValidator.php
@@ -19,7 +19,7 @@ final class OrderValidator {
* @param array $input Raw client params (goal_id, amount, display_name, anonymous, message, cover_fees).
* @param array $goal sg_goals row as array (id, currency, status, starts_at, ends_at).
* @param array $settings Settings::all()-shaped array.
- * @return array{goal_id:int,currency:string,base_minor:int,fee_minor:int,total_minor:int,donor_name:string,is_anonymous:bool,message:string,cover_fees:bool,moderation:string}
+ * @return array{goal_id:int,currency:string,base_minor:int,fee_minor:int,total_minor:int,donor_name:string,is_anonymous:bool,message:string,cover_fees:bool,moderation:string,moderation_flags:string}
* @throws ValidationException
*/
public static function validate( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array {
@@ -59,9 +59,20 @@ final class OrderValidator {
}
// Mask profanity before anything is stored (same-length masking, so length checks above still hold).
- $filter = new ProfanityFilter( $settings );
- $name = $filter->filter( $name );
- $message = $filter->filter( $message );
+ // A donor name that trips the filter is stored masked AND held for moderation (the donation still completes
+ // and counts). Anonymous names were blanked above, so they can never flag.
+ $filter = new ProfanityFilter( $settings );
+ $nameFlagged = '' !== $name && $filter->matches( $name );
+ $name = $filter->filter( $name );
+ $message = $filter->filter( $message );
+ $msgHeld = ! empty( $settings['moderate_messages'] ) && '' !== $message;
+ $flags = array();
+ if ( $nameFlagged ) {
+ $flags[] = 'name';
+ }
+ if ( $msgHeld ) {
+ $flags[] = 'message';
+ }
return array(
'goal_id' => (int) $goal['id'],
@@ -73,7 +84,8 @@ final class OrderValidator {
'is_anonymous' => $anon,
'message' => $message,
'cover_fees' => $cover,
- 'moderation' => ( ! empty( $settings['moderate_messages'] ) && '' !== $message ) ? 'pending' : 'approved',
+ 'moderation' => $flags ? 'pending' : 'approved',
+ 'moderation_flags' => implode( ',', $flags ), // '', 'name', 'message' or 'name,message' (why it is held)
);
}
diff --git a/includes/Tiers/Recorder.php b/includes/Tiers/Recorder.php
index a45ce9d..0a091e7 100644
--- a/includes/Tiers/Recorder.php
+++ b/includes/Tiers/Recorder.php
@@ -12,6 +12,11 @@ final class Recorder {
* @return int[] ids of the tiers this call unlocked.
*/
public static function forDonation( int $donationId ): array {
+ return self::forDonationChecked( $donationId ) ?? array();
+ }
+
+ /** Same as forDonation() but null (instead of an empty list) when something failed. Never throws. @return int[]|null */
+ public static function forDonationChecked( int $donationId ): ?array {
try {
global $wpdb;
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
@@ -27,7 +32,7 @@ final class Recorder {
return $repo->markReached( $goalId, $raised, $donationId );
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: tier unlock failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
- return array();
+ return null;
}
}
}
diff --git a/tests/Unit/DonorNameFlaggingTest.php b/tests/Unit/DonorNameFlaggingTest.php
new file mode 100644
index 0000000..381263e
--- /dev/null
+++ b/tests/Unit/DonorNameFlaggingTest.php
@@ -0,0 +1,92 @@
+ 3, 'currency' => 'USD', 'status' => 'active', 'starts_at' => null, 'ends_at' => null );
+ return OrderValidator::validate( $in + array( 'amount' => '10.00' ), $goal, array_merge( Settings::defaults(), array( 'moderate_messages' => false ), $settings ), new FeeCalculator( 349, 49 ), 1800000000 );
+ }
+
+ public function test_matches_agrees_with_filter(): void {
+ $f = new ProfanityFilter( array( 'profanity_words' => 'jerk' ) );
+ $this->assertTrue( $f->matches( 'Big Jerk' ) );
+ $this->assertTrue( $f->matches( 'sh1t head' ), 'leetspeak counts' );
+ $this->assertFalse( $f->matches( 'Scunthorpe class' ) );
+ $this->assertFalse( $f->matches( '' ) );
+ $this->assertFalse( ( new ProfanityFilter( array( 'profanity_filter' => false ) ) )->matches( 'shit' ) );
+ }
+
+ public function test_flagged_name_is_masked_and_held_even_when_message_moderation_is_off(): void {
+ $v = $this->validate( array( 'display_name' => 'Big Jerk', 'message' => 'thanks' ), array( 'profanity_words' => 'jerk' ) );
+ $this->assertSame( 'Big ****', $v['donor_name'] );
+ $this->assertSame( 'pending', $v['moderation'] );
+ $this->assertSame( 'name', $v['moderation_flags'] );
+ }
+
+ public function test_clean_name_and_off_switch_stay_approved(): void {
+ $v = $this->validate( array( 'display_name' => 'Ann', 'message' => 'hi' ) );
+ $this->assertSame( array( 'approved', '' ), array( $v['moderation'], $v['moderation_flags'] ) );
+ $v = $this->validate( array( 'display_name' => 'shit', 'message' => '' ), array( 'profanity_filter' => false ) );
+ $this->assertSame( array( 'approved', '' ), array( $v['moderation'], $v['moderation_flags'] ) );
+ $this->assertSame( 'shit', $v['donor_name'] );
+ }
+
+ public function test_message_only_and_both_flags(): void {
+ $v = $this->validate( array( 'display_name' => 'Ann', 'message' => 'hello' ), array( 'moderate_messages' => true ) );
+ $this->assertSame( array( 'pending', 'message' ), array( $v['moderation'], $v['moderation_flags'] ) );
+ $v = $this->validate( array( 'display_name' => 'shit', 'message' => 'hello' ), array( 'moderate_messages' => true ) );
+ $this->assertSame( array( 'pending', 'name,message' ), array( $v['moderation'], $v['moderation_flags'] ) );
+ $v = $this->validate( array( 'display_name' => 'shit', 'message' => '' ), array( 'moderate_messages' => true ) );
+ $this->assertSame( 'name', $v['moderation_flags'], 'empty message is never flagged' );
+ }
+
+ public function test_anonymous_donor_name_never_stored_and_never_flags(): void {
+ $v = $this->validate( array( 'display_name' => 'shit', 'anonymous' => true, 'message' => '' ) );
+ $this->assertSame( '', $v['donor_name'] );
+ $this->assertSame( array( 'approved', '' ), array( $v['moderation'], $v['moderation_flags'] ) );
+ $v = $this->validate( array( 'display_name' => 'shit', 'message' => '' ), array( 'anonymity_policy' => 'force_anonymous' ) );
+ $this->assertSame( 'approved', $v['moderation'] );
+ }
+
+ public function test_flagged_label(): void {
+ $this->assertSame( 'Name', Format::flaggedLabel( array( 'moderation_flags' => 'name' ) ) );
+ $this->assertSame( 'Message', Format::flaggedLabel( array( 'moderation_flags' => 'message' ) ) );
+ $this->assertSame( 'Name and message', Format::flaggedLabel( array( 'moderation_flags' => 'name,message' ) ) );
+ $this->assertSame( 'Message', Format::flaggedLabel( array( 'moderation_flags' => '' ) ), 'rows held before v6' );
+ $this->assertSame( 'Message', Format::flaggedLabel( array() ) );
+ }
+
+ public function test_alert_for_held_name_is_not_emitted_until_approved_then_shows_masked_name(): void {
+ $row = array( 'id' => 5, 'base_minor' => 500, 'currency' => 'USD', 'donor_name' => 'Big ****', 'is_anonymous' => 0,
+ 'message' => '', 'status' => 'completed', 'moderation' => 'pending' );
+ foreach ( array( 'pending', 'rejected' ) as $m ) {
+ foreach ( array( false, true ) as $recent ) {
+ $out = Payloads::alerts( array( array( 'moderation' => $m ) + $row ), 0, 10, $recent );
+ $this->assertSame( array(), $out['alerts'], "$m (recent=" . (int) $recent . ') must hold the whole alert' );
+ }
+ }
+ $out = Payloads::alerts( array( array( 'moderation' => 'approved' ) + $row ), 0 );
+ $this->assertSame( 'Big ****', $out['alerts'][0]['name'] );
+ }
+
+ public function test_flags_are_wired_through_storage_and_data_sources(): void {
+ $root = dirname( __DIR__, 2 ) . '/includes/';
+ $this->assertStringContainsString( "'moderation_flags' => (string)", (string) file_get_contents( $root . 'PayPal/DonationStore.php' ) );
+ $this->assertStringContainsString( 'moderation_flags VARCHAR(16) NOT NULL DEFAULT', (string) file_get_contents( $root . 'Core/Installer.php' ) );
+ foreach ( array( 'Overlay/WpdbDataSource.php', 'Core/DonationRepository.php' ) as $f ) {
+ $this->assertStringContainsString( "moderation = 'approved'", (string) file_get_contents( $root . $f ), $f );
+ }
+ }
+}
diff --git a/tests/Unit/EffectsReconciliationTest.php b/tests/Unit/EffectsReconciliationTest.php
new file mode 100644
index 0000000..55497e4
--- /dev/null
+++ b/tests/Unit/EffectsReconciliationTest.php
@@ -0,0 +1,339 @@
+sql[] = $q;
+ $row = array( 'id' => 7, 'goal_id' => 1, 'base_minor' => 500, 'fee_minor' => 0, 'total_minor' => 500, 'currency' => 'USD', 'status' => 'completed', 'close_at_target' => 0 );
+ return 'ARRAY_A' === $out ? $row : (object) $row;
+ }
+ public function get_results( string $q, $out = null ): array {
+ $this->sql[] = $q;
+ if ( $this->failRules && str_contains( $q, 'sg_rules' ) ) {
+ throw new \RuntimeException( 'db gone' );
+ }
+ return array();
+ }
+ public function get_var( string $q ) {
+ $this->sql[] = $q;
+ return str_contains( $q, 'GET_LOCK' ) ? 1 : null;
+ }
+ public function get_col( string $q ): array {
+ $this->sql[] = $q;
+ return $this->ids;
+ }
+ public function query( string $q ) {
+ $this->sql[] = $q;
+ return 1;
+ }
+ }
+ }
+}
+
+namespace StreamGoals\Tests\Unit {
+
+ use PHPUnit\Framework\TestCase;
+ use StreamGoals\Actions\ActionRepository;
+ use StreamGoals\Core\Installer;
+ use StreamGoals\Core\Maintenance;
+ use StreamGoals\PayPal\CaptureFinalizer;
+ use StreamGoals\PayPal\DonationStore;
+ use StreamGoals\Rules\Donation;
+ use StreamGoals\Rules\Engine;
+ use StreamGoals\Rules\RuleDef;
+ use StreamGoals\Tiers\TierRepository;
+
+ final class EffectsReconciliationTest extends TestCase {
+
+ private $prevDb;
+
+ protected function setUp(): void {
+ $this->prevDb = $GLOBALS['wpdb'] ?? null;
+ $GLOBALS['wpdb'] = new \wpdb();
+ }
+
+ protected function tearDown(): void {
+ $GLOBALS['wpdb'] = $this->prevDb;
+ }
+
+ private function stamps( object $db ): array {
+ return array_values( array_filter( $db->sql, static fn( $q ) => str_contains( $q, 'SET effects_applied_at' ) ) );
+ }
+
+ // ---- stamping ---------------------------------------------------------------------------------------
+
+ public function test_notify_applied_stamps_only_when_every_step_succeeded(): void {
+ $db = $GLOBALS['wpdb'];
+ $this->assertTrue( DonationStore::notify_applied( 7 ) );
+ $stamps = $this->stamps( $db );
+ $this->assertCount( 1, $stamps );
+ $this->assertStringContainsString( "WHERE id = 7 AND status = 'completed' AND effects_applied_at IS NULL", $stamps[0] );
+
+ $db->sql = array();
+ $db->failRules = true; // simulates the engine dying
+ $this->assertFalse( DonationStore::notify_applied( 7 ) );
+ $this->assertSame( array(), $this->stamps( $db ), 'a failed side effect must leave effects_applied_at NULL so reconcile retries' );
+ }
+
+ public function test_stamp_is_the_last_step_of_notify_applied(): void {
+ $src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/PayPal/DonationStore.php' );
+ $start = strpos( $src, 'function notify_applied' );
+ $body = substr( $src, $start, strpos( $src, 'function mark_effects_applied' ) - $start );
+ $this->assertLessThan( strpos( $body, 'mark_effects_applied' ), strpos( $body, 'close_goal_if_target_reached' ) );
+ $this->assertLessThan( strpos( $body, 'close_goal_if_target_reached' ), strpos( $body, 'Tiers\\Recorder::forDonationChecked' ), 'tiers still before close-at-target' );
+ }
+
+ public function test_capture_finalizer_still_runs_effects_once_even_if_replayed(): void {
+ $row = array( 'id' => 7, 'status' => 'pending', 'total_minor' => 500, 'currency' => 'USD' );
+ $state = (object) array( 'status' => 'pending', 'applied' => 0 );
+ $mark = static function () use ( $state ): bool {
+ if ( 'pending' !== $state->status ) {
+ return false;
+ }
+ $state->status = 'completed';
+ return true;
+ };
+ $notify = static function () use ( $state ): void {
+ $state->applied++;
+ };
+ $m = new \StreamGoals\Core\Money( 500, 'USD' );
+ $this->assertSame( 'completed', CaptureFinalizer::finalize( $row, 'COMPLETED', 'C1', $m, $mark, $notify ) );
+ $this->assertSame( 'duplicate', CaptureFinalizer::finalize( $row, 'COMPLETED', 'C1', $m, $mark, $notify ), 'webhook replay on a stale pending snapshot' );
+ $this->assertSame( 'duplicate', CaptureFinalizer::finalize( array( 'status' => 'completed' ) + $row, 'COMPLETED', 'C1', $m, $mark, $notify ) );
+ $this->assertSame( 1, $state->applied );
+ }
+
+ // ---- reconcile --------------------------------------------------------------------------------------
+
+ public function test_reconcile_window_batch_and_counting(): void {
+ $now = 1800000000;
+ $seen = array();
+ $n = Maintenance::reconcile(
+ $now,
+ function ( string $after, string $before, int $limit ) use ( &$seen ): array {
+ $seen = array( strtotime( $after . ' UTC' ), strtotime( $before . ' UTC' ), $limit );
+ return array( 4, 5, 6 );
+ },
+ static function ( int $id ): bool {
+ if ( 5 === $id ) {
+ throw new \RuntimeException( 'boom' );
+ }
+ return 4 === $id; // 6 "fails" (not stamped)
+ }
+ );
+ $this->assertSame( 1, $n, 'a throwing or failing donation neither aborts the batch nor counts as applied' );
+ $this->assertSame( $now - 120, $seen[0], 'only donations older than 2 minutes' );
+ $this->assertSame( $now - 30 * 86400, $seen[1] );
+ $this->assertSame( Maintenance::RECONCILE_BATCH, $seen[2] );
+ }
+
+ public function test_candidate_query_only_selects_completed_unstamped_real_goal_rows(): void {
+ $db = $GLOBALS['wpdb'];
+ $ids = DonationStore::unapplied_completed_ids( '2026-01-02 00:00:00', '2025-12-01 00:00:00', 25 );
+ $this->assertSame( array( 7 ), $ids );
+ $q = $db->sql[0];
+ $this->assertStringContainsString( "status = 'completed' AND effects_applied_at IS NULL AND goal_id > 0", $q );
+ $this->assertStringContainsString( "created_at < '2026-01-02 00:00:00' AND created_at >= '2025-12-01 00:00:00'", $q );
+ $this->assertStringNotContainsString( 'UPDATE', $q );
+ $this->assertStringNotContainsString( 'DELETE', $q );
+ }
+
+ public function test_reconcile_effects_is_single_flight_and_releases_the_lock(): void {
+ $db = $GLOBALS['wpdb'];
+ $this->assertSame( 1, Maintenance::reconcile_effects() ); // id 7 -> notify_applied -> stamped
+ $this->assertNotEmpty( array_filter( $db->sql, static fn( $q ) => str_contains( $q, 'RELEASE_LOCK' ) ) );
+ $this->assertCount( 1, $this->stamps( $db ) );
+
+ $busy = new class() extends \wpdb {
+ public function get_var( string $q ) {
+ $this->sql[] = $q;
+ return 0; // GET_LOCK denied
+ }
+ };
+ $GLOBALS['wpdb'] = $busy;
+ $this->assertSame( 0, Maintenance::reconcile_effects() );
+ $this->assertSame( array(), $this->stamps( $busy ) );
+ }
+
+ public function test_cron_schedule_and_hooks(): void {
+ $s = Maintenance::cron_schedules( array( 'daily' => array() ) );
+ $this->assertSame( 300, $s[ Maintenance::RECONCILE_SCHEDULE ]['interval'] );
+ $this->assertArrayHasKey( 'daily', $s );
+ $this->assertSame( 120, Maintenance::RECONCILE_MIN_AGE );
+ $root = dirname( __DIR__, 2 ) . '/includes/Core/';
+ $this->assertStringContainsString( 'wp_clear_scheduled_hook( self::RECONCILE_HOOK )', (string) file_get_contents( $root . 'Maintenance.php' ) );
+ $this->assertStringContainsString( 'Maintenance::RECONCILE_HOOK', (string) file_get_contents( $root . 'Uninstaller.php' ) );
+ }
+
+ // ---- upgrade ----------------------------------------------------------------------------------------
+
+ public function test_installer_v6_schema_and_backfill_ordering(): void {
+ $src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
+ $this->assertSame( '6', Installer::DB_VERSION );
+ $this->assertStringContainsString( 'effects_applied_at DATETIME NULL,', $src );
+ $this->assertStringContainsString( "moderation_flags VARCHAR(16) NOT NULL DEFAULT ''", $src );
+ $this->assertLessThan( strpos( $src, "update_option( 'sg_db_version'" ), strpos( $src, 'backfill_effects_applied()' ), 'version is only recorded after a successful backfill' );
+ }
+
+ public function test_backfill_runs_for_pre_v6_and_fresh_installs_only(): void {
+ foreach ( array( false, '', '1', '2', '5' ) as $from ) {
+ $this->assertTrue( Installer::needsEffectsBackfill( $from ), var_export( $from, true ) );
+ }
+ $this->assertFalse( Installer::needsEffectsBackfill( '6' ) );
+ $this->assertFalse( Installer::needsEffectsBackfill( '7' ) );
+ }
+
+ public function test_backfill_stamps_existing_completed_rows_once_and_reports_failure(): void {
+ $db = $GLOBALS['wpdb'];
+ $this->assertTrue( Installer::backfill_effects_applied() );
+ $q = $db->sql[0];
+ $this->assertStringContainsString( 'UPDATE wp_sg_donations SET effects_applied_at =', $q );
+ $this->assertStringContainsString( "WHERE status = 'completed' AND effects_applied_at IS NULL", $q );
+
+ $GLOBALS['wpdb'] = new class() extends \wpdb {
+ public function query( string $q ) {
+ return false;
+ }
+ };
+ $this->assertFalse( Installer::backfill_effects_applied() );
+ }
+
+ // ---- replay does not double-apply -------------------------------------------------------------------
+
+ private function rules(): array {
+ return array(
+ new RuleDef( 1, 1, 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ) ),
+ new RuleDef( 2, 1, 'counter', array( 'step' => 1, 'per_minor' => 1000, 'carry_over' => true ) ),
+ new RuleDef( 3, 1, 'bonus', array( 'min_minor' => 1000, 'event' => 'big' ) ),
+ );
+ }
+
+ public function test_engine_replay_after_full_apply_changes_nothing_and_fires_no_second_bonus(): void {
+ $state = new FakeStateRepository();
+ $ev = new FakeEventStore();
+ $fired = 0;
+ $e = new Engine( new FakeRuleStore( $this->rules() ), $ev, $state, fn(): int => 1000, function () use ( &$fired ): void {
+ $fired++;
+ } );
+ $d = new Donation( 10, 1, 2500, 0, 2500, 'USD' );
+ $e->applyDonation( $d );
+ $state1 = $state->data;
+ $ev1 = $ev->events;
+ $this->assertSame( 1, $fired );
+ for ( $i = 0; $i < 3; $i++ ) {
+ $e->applyDonation( $d );
+ }
+ $this->assertSame( $state1, $state->data, 'timer and counter untouched by replays' );
+ $this->assertSame( $ev1, $ev->events );
+ $this->assertSame( 1, $fired, 'bonus event fires once' );
+ }
+
+ public function test_engine_replay_after_partial_apply_only_applies_the_missing_rules(): void {
+ $state = new FakeStateRepository();
+ $ev = new FakeEventStore();
+ $d = new Donation( 10, 1, 2500, 0, 2500, 'USD' );
+ $rules = $this->rules();
+ // The process died after the timer rule (rule 1) but before the others.
+ ( new Engine( new FakeRuleStore( array( $rules[0] ) ), $ev, $state, fn(): int => 1000 ) )->applyDonation( $d );
+ $timer = $state->getInt( 1, 'timer_ends_at' );
+ $this->assertSame( 2500, $timer );
+ // Later (clock moved on) the reconciler replays with all rules.
+ ( new Engine( new FakeRuleStore( $rules ), $ev, $state, fn(): int => 5000 ) )->applyDonation( $d );
+ $this->assertSame( $timer, $state->getInt( 1, 'timer_ends_at' ), 'timer must not be added twice' );
+ $this->assertSame( 1500, $state->getInt( 1, 'timer_added:1' ) );
+ $this->assertSame( 2, $state->getInt( 1, 'counter:2' ), 'the lost counter effect is recovered' );
+ $this->assertSame( array( '1:10', '2:10', '3:10' ), array_keys( $ev->events ) );
+ }
+
+ public function test_action_events_replay_is_insert_ignore_on_the_unique_key(): void {
+ $db = new class() {
+ public string $prefix = 'wp_';
+ public array $rows = array();
+ public function prepare( string $q, ...$args ): string {
+ $i = 0;
+ return (string) preg_replace_callback( '/%[dsf]/', static function ( $m ) use ( &$i, $args ) {
+ $v = $args[ $i++ ];
+ return '%s' === $m[0] ? "'" . $v . "'" : (string) $v;
+ }, $q );
+ }
+ public function query( string $q ) {
+ if ( ! str_starts_with( $q, 'INSERT IGNORE' ) || ! preg_match( '/VALUES \((\d+), (\d+),/', $q, $m ) ) {
+ return 0;
+ }
+ $k = $m[1] . ':' . $m[2];
+ if ( isset( $this->rows[ $k ] ) ) {
+ return 0; // UNIQUE(donation_id, action_id) swallowed it
+ }
+ $this->rows[ $k ] = $q;
+ return 1;
+ }
+ };
+ $repo = new ActionRepository( $db );
+ $matches = array( array( 'action_id' => 4, 'title' => 'Beans', 'times' => 5 ), array( 'action_id' => 9, 'title' => 'Pushups', 'times' => 1 ) );
+ $repo->recordEvents( 10, $matches );
+ $repo->recordEvents( 10, $matches );
+ $this->assertCount( 2, $db->rows, 'one queued event per (donation, action) no matter how often it is replayed' );
+ $this->assertStringContainsString( 'UNIQUE KEY donation_action (donation_id,action_id)', (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' ) );
+ }
+
+ public function test_tier_marks_replay_does_not_reassign_or_re_mark(): void {
+ $db = new class() {
+ public string $prefix = 'wp_';
+ public array $tiers = array(
+ 1 => array( 'id' => '1', 'goal_id' => '7', 'target_minor' => '10000', 'title' => 'A', 'description' => '', 'reached_at' => null, 'reached_donation_id' => null, 'created_at' => '2026-01-01 00:00:00' ),
+ 2 => array( 'id' => '2', 'goal_id' => '7', 'target_minor' => '90000', 'title' => 'B', 'description' => '', 'reached_at' => null, 'reached_donation_id' => null, 'created_at' => '2026-01-01 00:00:00' ),
+ );
+ public function prepare( string $q, ...$args ): string {
+ $i = 0;
+ return (string) preg_replace_callback( '/%[dsf]/', static function ( $m ) use ( &$i, $args ) {
+ $v = $args[ $i++ ];
+ return '%s' === $m[0] ? "'" . $v . "'" : (string) $v;
+ }, $q );
+ }
+ public function get_results( string $q, $o = null ): array {
+ return array_values( $this->tiers );
+ }
+ public function query( string $q ) {
+ if ( ! preg_match( "/SET reached_at = '([^']+)', reached_donation_id = (\\d+) WHERE id = (\\d+) AND reached_at IS NULL/", $q, $m ) ) {
+ return 0;
+ }
+ if ( null !== $this->tiers[ (int) $m[3] ]['reached_at'] ) {
+ return 0;
+ }
+ $this->tiers[ (int) $m[3] ]['reached_at'] = $m[1];
+ $this->tiers[ (int) $m[3] ]['reached_donation_id'] = $m[2];
+ return 1;
+ }
+ };
+ $repo = new TierRepository( $db );
+ $this->assertSame( array( 1 ), $repo->markReached( 7, 20000, 55 ) );
+ $this->assertSame( array(), $repo->markReached( 7, 20000, 55 ), 'replay marks nothing' );
+ $this->assertSame( array(), $repo->markReached( 7, 20000, 56 ), 'a later replay never steals the unlock from donation 55' );
+ $this->assertSame( '55', $db->tiers[1]['reached_donation_id'] );
+ $this->assertNull( $db->tiers[2]['reached_at'] );
+ }
+
+ public function test_goal_close_is_conditional_so_replay_cannot_reclose(): void {
+ $src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/GoalRepository.php' );
+ $this->assertStringContainsString( "AND status = 'active' AND close_at_target = 1", $src );
+ $this->assertStringContainsString( "'active' !== \$goal['status']", $src );
+ }
+ }
+}