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 ); } } }