From 971a4ac482b2043bb5767a6b3f793593222b1255 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Fri, 27 Nov 2026 21:21:19 -0800 Subject: [PATCH] Add Replay button to show a donation alert again Donations > Replay queues the alert for the open alerts overlay. Requests expire after 60 seconds, play once, and never re-apply totals, timers, counters, rewards or tiers. Held, rejected and pending donations are excluded. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 3 ++ assets/overlay/overlay.js | 10 ++++ includes/Admin/Admin.php | 1 + includes/Admin/DonationsPage.php | 29 ++++++++++- includes/Admin/Store.php | 6 +++ includes/Core/Uninstaller.php | 1 + includes/Overlay/OverlayService.php | 24 ++++++--- includes/Overlay/Payloads.php | 22 ++++++++ includes/Overlay/ReplaySource.php | 19 +++++++ includes/Overlay/Replays.php | 52 ++++++++++++++++++ includes/Overlay/WpdbDataSource.php | 20 ++++++- tests/Unit/AlertReplayTest.php | 81 +++++++++++++++++++++++++++++ 12 files changed, 258 insertions(+), 10 deletions(-) create mode 100644 includes/Overlay/ReplaySource.php create mode 100644 includes/Overlay/Replays.php create mode 100644 tests/Unit/AlertReplayTest.php diff --git a/README.md b/README.md index 4f8084c..ba8de1d 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,9 @@ server sees. - **End at target:** tick "Close this goal to donations when the target is reached" on a goal. When the total reaches or passes the target (for a tiered goal, the final tier) the goal closes and the donation page says so. Donations already in checkout still go through. Use **Reopen** after raising the target. +- **Replay an alert:** StreamGoals > Donations, then **Replay** next to a donation. The alerts overlay shows it again + within a few seconds (it must be open at the time; a request expires after a minute). Totals, timers, counters, + rewards and tiers are not applied again. Held or rejected donations cannot be replayed. - **Test:** "Send test donation" on the Overlays screen shows an alert without touching real totals. ## Privacy and moderation diff --git a/assets/overlay/overlay.js b/assets/overlay/overlay.js index ddd8622..5ddd2e8 100644 --- a/assets/overlay/overlay.js +++ b/assets/overlay/overlay.js @@ -129,6 +129,7 @@ seenIds[id] = true; seenOrder.push(id); while (seenOrder.length > SEEN_MAX) delete seenIds[seenOrder.shift()]; } + var seenReplays = {}; function renderAlerts(d) { var list = (d.alerts || []).slice().sort(function (a, b) { return a.id - b.id; }); for (var i = 0; i < list.length; i++) { @@ -137,6 +138,15 @@ markSeen(a.id); if (!firstAlertPoll) queue.push(a); } + // Replays asked for in the admin: each request number plays once. Like new alerts, anything already on the + // feed at the first poll is only remembered, so refreshing OBS plays nothing. + var again = Array.isArray(d.replays) ? d.replays : []; + for (var j = 0; j < again.length; j++) { + var n = again[j].replay; + if (seenReplays[n]) continue; + seenReplays[n] = true; + if (!firstAlertPoll) queue.push(again[j]); + } firstAlertPoll = false; next(); } diff --git a/includes/Admin/Admin.php b/includes/Admin/Admin.php index 0f7dfe7..d72b09c 100644 --- a/includes/Admin/Admin.php +++ b/includes/Admin/Admin.php @@ -37,6 +37,7 @@ final class Admin { 'sg_event_done_all' => array( ActionsPage::class, 'handleDoneAll' ), 'sg_export_csv' => array( DonationsPage::class, 'handleExport' ), 'sg_moderate' => array( DonationsPage::class, 'handleModerate' ), + 'sg_replay_alert' => array( DonationsPage::class, 'handleReplay' ), 'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ), 'sg_delete_tests' => array( OverlaysPage::class, 'handleDeleteTests' ), 'sg_regen_token' => array( OverlaysPage::class, 'handleRegenerate' ), diff --git a/includes/Admin/DonationsPage.php b/includes/Admin/DonationsPage.php index a97973f..de11a87 100644 --- a/includes/Admin/DonationsPage.php +++ b/includes/Admin/DonationsPage.php @@ -4,6 +4,7 @@ declare( strict_types=1 ); namespace StreamGoals\Admin; use StreamGoals\Core\Settings; +use StreamGoals\Overlay\Replays; /** Donations table (search, filter, pagination), CSV export, and the message moderation queue. */ final class DonationsPage { @@ -34,6 +35,7 @@ final class DonationsPage { echo ''; echo '

Donors who chose to be anonymous are shown as "Anonymous". Their name is never stored. Test donations are marked TEST and left out of the CSV and your totals.

'; + echo '

Replay shows a donation\'s alert again on the Donation alerts overlay. The overlay must be open when you press it. Totals, timers and counters do not change.

'; if ( ! $res['rows'] ) { echo '

No donations found.

'; @@ -44,7 +46,7 @@ final class DonationsPage { foreach ( Store::goals()->all() as $g ) { $goals[ (int) $g['id'] ] = (string) $g['title']; } - echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Fee', 'Total paid', 'Goal', 'Status', 'Message' ), 'Donations', false ); + echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Fee', 'Total paid', 'Goal', 'Status', 'Message', 'Alert' ), 'Donations', false ); foreach ( $res['rows'] as $r ) { $cur = Format::currency( $r['currency'] ); $test = Format::isTest( $r ); @@ -53,7 +55,12 @@ final class DonationsPage { 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'] ? '' : ' ' . esc_html( strtolower( Format::flaggedLabel( $r ) ) . ' ' . (string) $r['moderation'] ) . '' ) . ''; - echo Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . ''; + echo Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '' . Admin::td( 'Alert', 'sg-actions' ); + if ( self::canReplay( $r ) ) { + Admin::form( 'sg_replay_alert', array( 'donation_id' => (int) $r['id'] ), 'sg-inline' ); + echo ''; + } + echo ''; } echo Admin::tableClose(); $pages = (int) ceil( $res['total'] / self::PER_PAGE ); @@ -71,6 +78,24 @@ final class DonationsPage { Admin::close(); } + /** Only donations that may appear on stream: paid, and not held or rejected by moderation. */ + public static function canReplay( array $row ): bool { + return 'completed' === ( $row['status'] ?? '' ) && 'approved' === ( $row['moderation'] ?? '' ); + } + + public static function handleReplay(): void { + Admin::guard( 'sg_replay_alert' ); + $post = Admin::post_raw(); + $id = isset( $post['donation_id'] ) ? absint( $post['donation_id'] ) : 0; + $row = $id ? Store::donationById( $id ) : null; + $ok = $row && self::canReplay( $row ); + if ( $ok ) { + Replays::request( $id ); + } + $back = wp_get_referer(); // keeps the current filter and page + Admin::redirect( $back ? $back : Admin::url( 'streamgoals-donations' ), $ok ? 'success' : 'error', $ok ? 'Alert sent again. Watch your alerts overlay.' : 'That donation cannot be replayed.' ); + } + public static function renderModeration(): void { Admin::open( 'Moderation' ); if ( ! Settings::get( 'moderate_messages' ) ) { diff --git a/includes/Admin/Store.php b/includes/Admin/Store.php index 8edbadb..a5c2138 100644 --- a/includes/Admin/Store.php +++ b/includes/Admin/Store.php @@ -152,6 +152,12 @@ final class Store { return (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND moderation = 'pending'" ); } + public static function donationById( int $id ): ?array { + global $wpdb; + $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id = %d', $id ), ARRAY_A ); + return $row ?: null; + } + public static function setModeration( int $id, string $to ): bool { global $wpdb; if ( ! in_array( $to, array( 'approved', 'rejected' ), true ) ) { diff --git a/includes/Core/Uninstaller.php b/includes/Core/Uninstaller.php index 01c0513..531f5b3 100644 --- a/includes/Core/Uninstaller.php +++ b/includes/Core/Uninstaller.php @@ -38,6 +38,7 @@ final class Uninstaller { 'sg_settings', 'sg_db_version', 'sg_overlay_epoch', + 'sg_alert_replays', 'sg_overlay_rules_version', 'sg_currency', 'sg_paypal_verified', diff --git a/includes/Overlay/OverlayService.php b/includes/Overlay/OverlayService.php index ba1ec41..080165a 100644 --- a/includes/Overlay/OverlayService.php +++ b/includes/Overlay/OverlayService.php @@ -53,15 +53,20 @@ final class OverlayService { } else { $rows = $this->source->donations( $since, 20 ); } - $ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) ); + // Replays travel beside the normal feed and may point at donations older than the recent window. + $requests = ( $recent && $this->source instanceof ReplaySource ) ? $this->source->pendingReplays( $now ) : array(); + $replayRows = $requests ? $this->source->donationsByIds( array_column( $requests, 'id' ) ) : array(); + $ids = array_values( array_unique( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), array_merge( $rows, $replayRows ) ) ) ) ); $bonuses = ( ( $recent || null !== $since ) && $ids ) ? $this->source->bonusesFor( $ids ) : array(); $actions = ( ( $recent || null !== $since ) && $ids && $this->source instanceof ActionsSource ) ? $this->source->actionsFor( $ids ) : array(); $tiers = ( ( $recent || null !== $since ) && $ids && $this->source instanceof TiersSource ) ? $this->source->tiersReachedFor( $ids ) : array(); - foreach ( $rows as $i => $r ) { - $rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array(); - $rows[ $i ]['actions'] = $actions[ (int) ( $r['id'] ?? 0 ) ] ?? array(); - $rows[ $i ]['tiers'] = $tiers[ (int) ( $r['id'] ?? 0 ) ] ?? array(); - } + $decorate = static fn( array $r ): array => array( + 'bonuses' => $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array(), + 'actions' => $actions[ (int) ( $r['id'] ?? 0 ) ] ?? array(), + 'tiers' => $tiers[ (int) ( $r['id'] ?? 0 ) ] ?? array(), + ) + $r; + $rows = array_map( $decorate, $rows ); + $replayRows = array_map( $decorate, $replayRows ); $mediaFor = null; $defs = ( $recent || null !== $since ) ? $this->defs() : array(); if ( $defs && $ids && $this->source instanceof AlertMediaSource ) { @@ -71,7 +76,12 @@ final class OverlayService { $r, $name, $amount, $defs, $triggered[ (int) ( $r['id'] ?? 0 ) ] ?? array(), static fn( int $id ): ?array => $src->attachment( $id ) ); } - return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent, $mediaFor ); + $out = Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent, $mediaFor ); + $replays = Payloads::replays( $replayRows, $requests, $mediaFor ); + if ( $replays ) { + $out['replays'] = $replays; + } + return $out; case 'actions': $rows = ( $gid && $this->source instanceof ActionsSource ) ? $this->source->menuActions( $gid ) : array(); return Payloads::actionsMenu( $goal, $rows ); diff --git a/includes/Overlay/Payloads.php b/includes/Overlay/Payloads.php index bf59f98..1aad493 100644 --- a/includes/Overlay/Payloads.php +++ b/includes/Overlay/Payloads.php @@ -154,6 +154,28 @@ final class Payloads { return array( 'alerts' => $alerts, 'last_id' => $lastId ); } + /** + * One alert per replay request whose donation is still public, in request order, tagged with the request number. + * + * @param array> $rows + * @param array $requests + */ + public static function replays( array $rows, array $requests, ?callable $mediaFor = null ): array { + $byId = array(); + foreach ( $rows as $r ) { + if ( 'completed' === ( $r['status'] ?? '' ) && 'approved' === ( $r['moderation'] ?? '' ) ) { + $byId[ (int) $r['id'] ] = $r; + } + } + $out = array(); + foreach ( $requests as $q ) { + if ( isset( $byId[ (int) $q['id'] ] ) ) { + $out[] = array( 'replay' => (int) $q['seq'] ) + self::alert( $byId[ (int) $q['id'] ], $mediaFor ); + } + } + return $out; + } + /** * @param array $r * @param (callable(array,string,string):?array)|null $mediaFor Builds the `media` block from (row, public name, amount display). diff --git a/includes/Overlay/ReplaySource.php b/includes/Overlay/ReplaySource.php new file mode 100644 index 0000000..98851bf --- /dev/null +++ b/includes/Overlay/ReplaySource.php @@ -0,0 +1,19 @@ + Unexpired replay requests, oldest first. */ + public function pendingReplays( int $now ): array; + + /** + * The completed + approved donations among $ids, any age. + * + * @param int[] $ids + * @return array> + */ + public function donationsByIds( array $ids ): array; +} diff --git a/includes/Overlay/Replays.php b/includes/Overlay/Replays.php new file mode 100644 index 0000000..dc65457 --- /dev/null +++ b/includes/Overlay/Replays.php @@ -0,0 +1,52 @@ + + */ + public static function active( mixed $stored, int $now ): array { + $out = array(); + foreach ( is_array( $stored ) ? $stored : array() as $r ) { + if ( ! is_array( $r ) || ! isset( $r['seq'], $r['id'], $r['at'] ) || (int) $r['id'] <= 0 || $now - (int) $r['at'] >= self::TTL ) { + continue; + } + $out[] = array( 'seq' => (int) $r['seq'], 'id' => (int) $r['id'], 'at' => (int) $r['at'] ); + } + return $out; + } + + /** Pure: the queue after asking for $donationId again. The number never drops below the clock, so it cannot repeat after the queue empties. */ + public static function push( mixed $stored, int $donationId, int $now ): array { + $list = self::active( $stored, $now ); + $last = $list ? max( array_column( $list, 'seq' ) ) : 0; + $list[] = array( 'seq' => max( $last + 1, $now ), 'id' => $donationId, 'at' => $now ); + return array_slice( $list, -self::MAX ); + } + + public static function request( int $donationId ): void { + update_option( self::OPTION, self::push( get_option( self::OPTION, array() ), $donationId, time() ), false ); + } + + /** @return array */ + public static function pending( int $now ): array { + return self::active( get_option( self::OPTION, array() ), $now ); + } +} diff --git a/includes/Overlay/WpdbDataSource.php b/includes/Overlay/WpdbDataSource.php index c96a008..3c09128 100644 --- a/includes/Overlay/WpdbDataSource.php +++ b/includes/Overlay/WpdbDataSource.php @@ -4,7 +4,7 @@ declare( strict_types=1 ); namespace StreamGoals\Overlay; /** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */ -final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource, TiersSource { +final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource, TiersSource, ReplaySource { /** @var array */ private array $attachments = array(); @@ -184,6 +184,24 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, return (array) $rows; } + public function pendingReplays( int $now ): array { + return Replays::pending( $now ); + } + + public function donationsByIds( array $ids ): array { + global $wpdb; + $ids = array_values( array_unique( array_filter( array_map( 'intval', $ids ), static fn( $i ) => $i > 0 ) ) ); + if ( ! $ids ) { + return array(); + } + $in = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); + return (array) $wpdb->get_results( $wpdb->prepare( + "SELECT id, goal_id, base_minor, currency, donor_name, is_anonymous, message, status, moderation FROM {$this->t('donations')} + WHERE status = 'completed' AND moderation = 'approved' AND id IN ($in)", + $ids + ), ARRAY_A ); + } + public function recentDonations( int $limit ): array { global $wpdb; $rows = $wpdb->get_results( $wpdb->prepare( diff --git a/tests/Unit/AlertReplayTest.php b/tests/Unit/AlertReplayTest.php new file mode 100644 index 0000000..f7f69bf --- /dev/null +++ b/tests/Unit/AlertReplayTest.php @@ -0,0 +1,81 @@ + $id, 'base_minor' => 500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0, + 'message' => '', 'status' => 'completed', 'moderation' => 'approved' ); + } + + /** Donation 1 is older than the recent window; only 2 is "recent". */ + private function svc( array $db, array $requests ): OverlayService { + return new OverlayService( new class( $db, $requests ) implements OverlayDataSource, RecentDonationsSource, ReplaySource { + public function __construct( private array $db, private array $requests ) {} + public function activeGoal(): ?array { return null; } + public function raisedMinor( array $goal ): int { return 0; } + public function stateValue( int $goalId, string $key ): ?string { return null; } + public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); } + public function bonusesFor( array $ids ): array { return array_fill_keys( $ids, array( 'big_donation' ) ); } + public function donations( ?int $sinceId, int $limit ): array { return array(); } + public function recentDonations( int $limit ): array { return array_slice( $this->db, -1 ); } + public function pendingReplays( int $now ): array { return $this->requests; } + public function donationsByIds( array $ids ): array { return array_values( array_filter( $this->db, static fn( $d ) => in_array( $d['id'], $ids, true ) ) ); } + } ); + } + + public function test_old_donation_is_replayed_with_its_extras_once_per_request(): void { + $svc = $this->svc( array( $this->row( 1 ), $this->row( 2 ) ), array( array( 'seq' => 100, 'id' => 1 ), array( 'seq' => 101, 'id' => 1 ) ) ); + $out = $svc->payload( 'alerts', 1, null, true ); + $this->assertSame( array( 2 ), array_column( $out['alerts'], 'id' ) ); + $this->assertSame( array( 100, 101 ), array_column( $out['replays'], 'replay' ) ); + $this->assertSame( array( 1, 1 ), array_column( $out['replays'], 'id' ) ); + $this->assertSame( array( 'Big donation' ), $out['replays'][0]['bonuses'] ); + $this->assertSame( array( 'Big donation' ), $out['alerts'][0]['bonuses'] ); + } + + public function test_no_requests_leaves_the_payload_and_etag_unchanged(): void { + $out = $this->svc( array( $this->row( 2 ) ), array() )->payload( 'alerts', 1, null, true ); + $this->assertSame( array( 'alerts', 'last_id' ), array_keys( $out ) ); + $with = $this->svc( array( $this->row( 2 ) ), array( array( 'seq' => 5, 'id' => 2 ) ) )->payload( 'alerts', 1, null, true ); + $this->assertNotSame( Payloads::etag( $out ), Payloads::etag( $with ) ); + } + + public function test_held_rejected_and_pending_donations_are_never_replayed_and_names_stay_masked(): void { + $rows = array( $this->row( 1, array( 'moderation' => 'pending' ) ), $this->row( 2, array( 'moderation' => 'rejected' ) ), + $this->row( 3, array( 'status' => 'pending' ) ), $this->row( 4, array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ) ); + $requests = array_map( static fn( $i ) => array( 'seq' => $i, 'id' => $i ), array( 1, 2, 3, 4, 99 ) ); + $out = Payloads::replays( $rows, $requests ); + $this->assertSame( array( 4 ), array_column( $out, 'id' ) ); + $this->assertSame( 'Anonymous', $out[0]['name'] ); + foreach ( array_slice( $rows, 0, 3 ) as $r ) { + $this->assertFalse( DonationsPage::canReplay( $r ) ); + } + $this->assertTrue( DonationsPage::canReplay( $rows[3] ) ); + } + + public function test_queue_numbers_increase_expire_and_are_capped(): void { + $q = Replays::push( false, 7, 1000 ); + $q = Replays::push( $q, 7, 1000 ); + $this->assertSame( array( 1000, 1001 ), array_column( $q, 'seq' ) ); + $this->assertCount( 2, Replays::active( $q, 1000 + Replays::TTL - 1 ) ); + $this->assertSame( array(), Replays::active( $q, 1000 + Replays::TTL ) ); + $this->assertSame( array( 2000 ), array_column( Replays::push( $q, 8, 2000 ), 'seq' ) ); + for ( $i = 0; $i < 30; $i++ ) { + $q = Replays::push( $q, 7, 1000 ); + } + $this->assertCount( Replays::MAX, $q ); + $this->assertSame( array(), Replays::active( array( 'junk', array( 'seq' => 1 ) ), 1000 ) ); + } +}