Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 11ac72b23b Test: pin down which rows the abandoned-checkout purge may delete
Test and Release / test (push) Successful in 1m20s
Test and Release / release (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:30:21 -08:00
shadowdaoandClaude Sonnet 5.5 f7ff1dc717 Alerts overlay: show messages approved after later donations (recent mode with client-side dedupe)
Test and Release / test (push) Successful in 1m10s
Test and Release / release (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:26:03 -08:00
shadowdaoandClaude Sonnet 5.5 875ca42054 CSV export: only completed donations (not abandoned checkouts)
Test and Release / test (push) Successful in 1m18s
Test and Release / release (push) Successful in 4s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:14:04 -08:00
shadowdaoandClaude Sonnet 5.5 c7f2dcffeb Make bonus rules visible: highlighted BONUS line on the alerts overlay, streamgoals_bonus action
Test and Release / test (push) Successful in 1m14s
Test and Release / release (push) Successful in 4s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:07:06 -08:00
15 changed files with 421 additions and 24 deletions

No files matched your search

+6 -1
View File
@@ -27,7 +27,12 @@ body.sg-offline #sg-root{opacity:.6}
.sg-alert-head{font-weight:800;font-size:1.2em}
.sg-alert-head b{color:var(--sg-accent2)}
.sg-alert-msg{margin-top:.3em;font-size:.85em;overflow-wrap:anywhere;max-height:5.2em;overflow:hidden}
.sg-alert.sg-bonus{border-width:.14em;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both,sg-glow 1.4s ease-in-out .6s infinite}
.sg-alert.sg-bonus.sg-out{animation:sg-out .5s ease-in both}
.sg-bonus-line{margin-top:.3em;display:inline-block;padding:.1em .6em;border-radius:999px;font-weight:900;font-size:.95em;letter-spacing:.06em;text-transform:uppercase;color:#fff;background:linear-gradient(90deg,var(--sg-accent),var(--sg-accent2));text-shadow:0 1px 3px rgba(0,0,0,.6);box-shadow:0 0 0 .08em rgba(0,0,0,.45)}
.sg-bonus-line+.sg-bonus-line{margin-left:.4em}
@keyframes sg-glow{0%,100%{box-shadow:0 0 .4em var(--sg-accent),0 0 .9em var(--sg-accent2)}50%{box-shadow:0 0 .9em var(--sg-accent),0 0 1.9em var(--sg-accent2)}}
@keyframes sg-in{from{opacity:0;transform:translateY(40%) scale(.9)}to{opacity:1;transform:none}}
@keyframes sg-out{to{opacity:0;transform:translateY(-30%) scale(.95)}}
@keyframes sg-blink{50%{opacity:.4}}
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out{animation:none}}
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out,.sg-alert.sg-bonus,.sg-alert.sg-bonus.sg-out{animation:none}.sg-alert.sg-bonus{box-shadow:0 0 .8em var(--sg-accent2)}}
+27 -4
View File
@@ -5,7 +5,7 @@
var endpoint = body.getAttribute('data-endpoint');
var poll = Math.max(1000, parseInt(body.getAttribute('data-poll'), 10) || 2500);
var root = document.getElementById('sg-root');
var etag = null, failures = 0, since = null, skew = 0, timerState = null;
var etag = null, failures = 0, skew = 0, timerState = null;
var queue = [], showing = false;
function el(tag, cls, text) {
@@ -92,9 +92,25 @@
}
// ---- alerts ----
// Why not a `since` cursor: with moderation, a held donation keeps a low id. If a newer donation is shown
// first, the cursor moves past it and the later approval would never be returned. So we poll ?recent=1
// (newest 20 approved alerts) and dedupe by id here. First successful poll only seeds seenIds, so
// refreshing OBS never replays old alerts. Limit: a message approved after 20+ newer donations is
// no longer in the window and is not shown.
var seenIds = {}, seenOrder = [], firstAlertPoll = true, SEEN_MAX = 200;
function markSeen(id) {
seenIds[id] = true; seenOrder.push(id);
while (seenOrder.length > SEEN_MAX) delete seenIds[seenOrder.shift()];
}
function renderAlerts(d) {
since = d.last_id;
for (var i = 0; i < d.alerts.length; i++) queue.push(d.alerts[i]);
var list = (d.alerts || []).slice().sort(function (a, b) { return a.id - b.id; });
for (var i = 0; i < list.length; i++) {
var a = list[i];
if (seenIds[a.id]) continue;
markSeen(a.id);
if (!firstAlertPoll) queue.push(a);
}
firstAlertPoll = false;
next();
}
function next() {
@@ -108,6 +124,13 @@
head.appendChild(document.createTextNode(' donated '));
head.appendChild(el('b', null, a.amount_display));
card.appendChild(head);
var bonuses = Array.isArray(a.bonuses) ? a.bonuses : [];
if (bonuses.length) {
card.classList.add('sg-bonus');
for (var j = 0; j < bonuses.length; j++) {
card.appendChild(el('div', 'sg-bonus-line', 'BONUS: ' + String(bonuses[j]) + '!'));
}
}
if (a.message) card.appendChild(el('div', 'sg-alert-msg', a.message));
root.appendChild(card);
setTimeout(function () {
@@ -119,7 +142,7 @@
// ---- polling ----
function url() {
var u = endpoint;
if (widget === 'alerts' && since !== null) u += (u.indexOf('?') < 0 ? '?' : '&') + 'since=' + encodeURIComponent(since);
if (widget === 'alerts') u += (u.indexOf('?') < 0 ? '?' : '&') + 'recent=1';
return u;
}
function schedule() {
+1 -1
View File
@@ -137,7 +137,7 @@ final class Store {
global $wpdb;
return (array) $wpdb->get_results(
$wpdb->prepare(
'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id > %d AND paypal_order_id NOT LIKE %s AND goal_id > 0 ORDER BY id ASC LIMIT %d',
'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id > %d AND status = \'completed\' AND paypal_order_id NOT LIKE %s AND goal_id > 0 ORDER BY id ASC LIMIT %d',
$afterId,
$wpdb->esc_like( Format::TEST_PREFIX ) . '%',
$limit
+9
View File
@@ -28,4 +28,13 @@ interface OverlayDataSource {
* @return array<int,array<string,mixed>>
*/
public function donations( ?int $sinceId, int $limit ): array;
/**
* Bonus event names that fired (and were not reversed) per donation, in firing order. One lookup
* for the whole page. Raw stored strings; Payloads sanitizes them. Donations without bonuses may be omitted.
*
* @param int[] $donationIds
* @return array<int,string[]> donation id => event names
*/
public function bonusesFor( array $donationIds ): array;
}
+17 -2
View File
@@ -10,7 +10,7 @@ final class OverlayService {
public function __construct( private OverlayDataSource $source ) {}
public function payload( string $widget, int $now, ?int $since = null ): ?array {
public function payload( string $widget, int $now, ?int $since = null, bool $recent = false ): ?array {
$goal = $this->source->activeGoal();
$gid = $goal ? (int) $goal['id'] : 0;
switch ( $widget ) {
@@ -26,7 +26,22 @@ final class OverlayService {
$c = $gid ? $this->source->counter( $gid ) : array( 'label' => '', 'value' => 0 );
return Payloads::counter( $c['label'], $c['value'] );
case 'alerts':
return Payloads::alerts( $this->source->donations( $since, 20 ), $since );
if ( $recent ) {
// Newest 20 approved rows regardless of cursor. Sources that predate RecentDonationsSource
// fall back to the oldest 20 (still correct for small installs, just not "newest").
$rows = $this->source instanceof RecentDonationsSource
? $this->source->recentDonations( 20 )
: $this->source->donations( 0, 20 );
$since = null;
} else {
$rows = $this->source->donations( $since, 20 );
}
$ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) );
$bonuses = ( ( $recent || null !== $since ) && $ids ) ? $this->source->bonusesFor( $ids ) : array();
foreach ( $rows as $i => $r ) {
$rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array();
}
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent );
}
return null;
}
+55 -13
View File
@@ -74,9 +74,11 @@ final class Payloads {
/**
* @param array<int,array<string,mixed>> $rows
* @param int|null $since Null means "first poll": no alerts, just a baseline last_id.
* @param int|null $since Null means "first poll": no alerts, just a baseline last_id.
* @param bool $recent Recent mode: ignore $since and return the newest $limit approved alerts (ascending id),
* so a message approved after newer donations still shows up. The client dedupes by id.
*/
public static function alerts( array $rows, ?int $since, int $limit = 10 ): array {
public static function alerts( array $rows, ?int $since, int $limit = 10, bool $recent = false ): array {
$safe = array();
foreach ( $rows as $r ) {
if ( 'completed' !== ( $r['status'] ?? '' ) || 'approved' !== ( $r['moderation'] ?? '' ) ) {
@@ -85,6 +87,11 @@ final class Payloads {
$safe[] = $r;
}
usort( $safe, static fn( $a, $b ) => (int) $a['id'] <=> (int) $b['id'] );
if ( $recent ) {
$safe = array_slice( $safe, -max( 1, $limit ) );
$alerts = array_map( array( self::class, 'alert' ), $safe );
return array( 'alerts' => $alerts, 'last_id' => $alerts ? (int) end( $alerts )['id'] : 0 );
}
$lastId = $since ?? 0;
foreach ( $safe as $r ) {
$lastId = max( $lastId, (int) $r['id'] );
@@ -97,17 +104,7 @@ final class Payloads {
if ( (int) $r['id'] <= $since ) {
continue;
}
$cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) );
$anon = ! empty( $r['is_anonymous'] );
$name = trim( (string) ( $r['donor_name'] ?? '' ) );
$alerts[] = array(
'id' => (int) $r['id'],
'name' => ( $anon || '' === $name ) ? self::ANON_NAME : $name,
'amount_minor' => (int) $r['base_minor'],
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
'currency' => $cur,
'message' => (string) ( $r['message'] ?? '' ),
);
$alerts[] = self::alert( $r );
}
$alerts = array_slice( $alerts, 0, max( 1, $limit ) );
if ( $alerts ) {
@@ -116,6 +113,51 @@ final class Payloads {
return array( 'alerts' => $alerts, 'last_id' => $lastId );
}
/** @param array<string,mixed> $r */
private static function alert( array $r ): array {
$cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) );
$anon = ! empty( $r['is_anonymous'] );
$name = trim( (string) ( $r['donor_name'] ?? '' ) );
return array(
'id' => (int) $r['id'],
'name' => ( $anon || '' === $name ) ? self::ANON_NAME : $name,
'amount_minor' => (int) $r['base_minor'],
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
'currency' => $cur,
'message' => (string) ( $r['message'] ?? '' ),
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
);
}
/**
* Display-safe bonus labels. Stored events should be [A-Za-z0-9_-] only; anything else is stripped
* anyway, then humanized ("big_donation" -> "Big donation"). Empty/duplicate results are dropped.
*
* @param mixed $events
* @return string[]
*/
public static function bonuses( mixed $events ): array {
$out = array();
foreach ( is_array( $events ) ? $events : array() as $e ) {
if ( ! is_string( $e ) ) {
continue;
}
$clean = substr( (string) preg_replace( '/[^A-Za-z0-9_-]/', '', $e ), 0, 40 );
$label = trim( (string) preg_replace( '/[_-]+/', ' ', $clean ) );
if ( '' === $label ) {
continue;
}
$label = ucfirst( strtolower( $label ) );
if ( ! in_array( $label, $out, true ) ) {
$out[] = $label;
}
if ( count( $out ) >= 5 ) {
break;
}
}
return $out;
}
/** Strong ETag over the payload, ignoring the volatile server_now so unchanged data yields 304s. */
public static function etag( array $payload ): string {
unset( $payload['server_now'] );
@@ -0,0 +1,15 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
/** Optional capability: the newest approved donations, independent of any client cursor. */
interface RecentDonationsSource {
/**
* The $limit newest completed + approved donations, ascending id.
*
* @return array<int,array<string,mixed>>
*/
public function recentDonations( int $limit ): array;
}
+36 -1
View File
@@ -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 {
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource {
private function t( string $name ): string {
global $wpdb;
@@ -62,6 +62,31 @@ final class WpdbDataSource implements OverlayDataSource {
return array( 'label' => $label, 'value' => $total );
}
public function bonusesFor( array $donationIds ): array {
global $wpdb;
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
if ( ! $ids ) {
return array();
}
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT e.donation_id, r.config FROM {$this->t('rule_events')} e
INNER JOIN {$this->t('rules')} r ON r.id = e.rule_id
WHERE r.type = 'bonus' AND e.reversed = 0 AND e.delta > 0 AND e.donation_id IN ($in)
ORDER BY e.id ASC",
$ids
), ARRAY_A );
$out = array();
foreach ( (array) $rows as $row ) {
$cfg = json_decode( (string) $row['config'], true );
$ev = is_array( $cfg ) && isset( $cfg['event'] ) && is_string( $cfg['event'] ) ? $cfg['event'] : '';
if ( '' !== $ev ) {
$out[ (int) $row['donation_id'] ][] = $ev;
}
}
return $out;
}
public function donations( ?int $sinceId, int $limit ): array {
global $wpdb;
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
@@ -77,4 +102,14 @@ final class WpdbDataSource implements OverlayDataSource {
}
return (array) $rows;
}
public function recentDonations( int $limit ): array {
global $wpdb;
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT id, base_minor, currency, donor_name, is_anonymous, message, status, moderation FROM {$this->t('donations')}
WHERE status = 'completed' AND moderation = 'approved' ORDER BY id DESC LIMIT %d",
max( 1, $limit )
), ARRAY_A );
return array_reverse( (array) $rows );
}
}
+3 -1
View File
@@ -24,6 +24,7 @@ final class OverlayController {
'permission_callback' => '__return_true', // capability is the unguessable token, checked in handle()
'args' => array(
'since' => array( 'type' => 'integer', 'minimum' => 0, 'sanitize_callback' => 'absint' ),
'recent' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 1, 'sanitize_callback' => 'absint' ),
),
) );
}
@@ -47,7 +48,8 @@ final class OverlayController {
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
}
$since = $req->has_param( 'since' ) && '' !== (string) $req->get_param( 'since' ) ? absint( $req->get_param( 'since' ) ) : null;
$payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since );
$recent = $req->has_param( 'recent' ) && 1 === absint( $req->get_param( 'recent' ) );
$payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since, $recent );
if ( null === $payload ) {
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
}
+14 -1
View File
@@ -19,7 +19,20 @@ final class Engine {
/** Production wiring: $wpdb-backed stores. */
public static function default(): self {
return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore() );
$onBonus = static function ( string $event, RuleDef $rule, Donation $d, bool $reversed ): void {
if ( function_exists( 'do_action' ) ) {
/**
* Fires when a big-donation bonus rule triggers (or is reversed by a refund).
*
* @param string $event Rule's event name.
* @param int $donationId Donation id.
* @param int $ruleId Rule id.
* @param bool $reversed True when the bonus was undone.
*/
do_action( 'streamgoals_bonus', $event, $d->id, $rule->id, $reversed );
}
};
return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore(), null, $onBonus );
}
/**
+16
View File
@@ -52,4 +52,20 @@ final class AdminStoreRulesTest extends TestCase {
$this->assertIsArray( $r['config'] );
$this->assertNull( Store::rule( 99, 1 ) );
}
public function test_export_only_selects_completed_non_test_donations(): void {
$captured = array();
$GLOBALS['wpdb'] = new class( $captured ) {
public string $prefix = 'wp_';
public function __construct( public array &$sql ) {}
public function esc_like( string $s ): string { return $s; }
public function prepare( string $q, ...$args ): string { return $q; }
public function get_results( string $q, $output = null ): array { $this->sql[] = $q; return array(); }
};
Store::exportBatch( 0, 100 );
$this->assertNotEmpty( $captured );
$this->assertStringContainsString( "status = 'completed'", $captured[0], 'abandoned/unpaid checkouts must not be exported' );
$this->assertStringContainsString( 'goal_id > 0', $captured[0], 'test donations must not be exported' );
}
}
@@ -39,6 +39,7 @@ final class EngineToOverlayIntegrationTest extends TestCase {
}
public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => $this->s->getInt( $goalId, 'counter:2' ) ); }
public function donations( ?int $sinceId, int $limit ): array { return array(); }
public function bonusesFor( array $donationIds ): array { return array(); }
} );
$d = new Donation( 7, 1, 2500, 0, 2500, 'USD' ); // $25 -> +25 min, counter +2
@@ -53,4 +54,55 @@ final class EngineToOverlayIntegrationTest extends TestCase {
$engine->reverseDonation( $d );
$this->assertSame( 0, $svc->payload( 'counter', $now )['value'] );
}
private function bonusOverlay( FakeEventStore $events, array $donations ): OverlayService {
return new OverlayService( new class( $events, $donations ) implements OverlayDataSource {
public function __construct( private FakeEventStore $ev, private array $rows ) {}
public function activeGoal(): ?array { return array( 'id' => 1, 'title' => 'G', 'target_minor' => 5000, 'currency' => 'USD' ); }
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 donations( ?int $sinceId, int $limit ): array { return $this->rows; }
public function bonusesFor( array $donationIds ): array {
$out = array();
foreach ( $this->ev->events as $k => $e ) {
[ , $did ] = array_map( 'intval', explode( ':', $k ) );
if ( 1 === $e[0] && ! $e[1] && in_array( $did, $donationIds, true ) ) {
$out[ $did ][] = 'big_donation';
}
}
return $out;
}
} );
}
public function test_bonus_over_threshold_visible_in_alerts_below_is_not_and_refund_removes(): void {
$events = new FakeEventStore();
$fired = array();
$engine = new Engine(
new FakeRuleStore( array( new RuleDef( 3, 1, 'bonus', array( 'min_minor' => 5000, 'event' => 'big_donation' ) ) ) ),
$events,
new FakeStateRepository(),
null,
function ( string $event, RuleDef $r, Donation $d, bool $rev ) use ( &$fired ): void {
$fired[] = array( $event, $d->id, $rev );
}
);
$big = new Donation( 10, 1, 5000, 0, 5000, 'USD' );
$small = new Donation( 11, 1, 4999, 0, 4999, 'USD' );
$engine->applyDonation( $big );
$engine->applyDonation( $small );
$this->assertSame( array( array( 'big_donation', 10, false ) ), $fired );
$row = static fn( int $id ): array => array( 'id' => $id, 'base_minor' => 5000, 'currency' => 'USD', 'donor_name' => 'A',
'is_anonymous' => 0, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
$svc = $this->bonusOverlay( $events, array( $row( 10 ), $row( 11 ) ) );
$alerts = $svc->payload( 'alerts', 1, 0 )['alerts'];
$this->assertSame( array( 'Big donation' ), $alerts[0]['bonuses'] );
$this->assertSame( array(), $alerts[1]['bonuses'] );
$engine->reverseDonation( $big );
$this->assertSame( array(), $svc->payload( 'alerts', 1, 0 )['alerts'][0]['bonuses'] );
$this->assertSame( true, $fired[1][2] );
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\Maintenance;
/**
* The purge deletes rows, so pin down exactly what it may touch: only never-paid pending checkouts,
* only older than a week, never test donations, never anything with a PayPal capture id.
*/
final class MaintenancePurgeTest extends TestCase {
private $previous;
protected function setUp(): void {
foreach ( array( 'HOUR_IN_SECONDS' => 3600, 'DAY_IN_SECONDS' => 86400 ) as $k => $v ) {
if ( ! defined( $k ) ) {
define( $k, $v );
}
}
$this->previous = $GLOBALS['wpdb'] ?? null;
}
protected function tearDown(): void {
$GLOBALS['wpdb'] = $this->previous;
}
public function test_purge_sql_only_targets_abandoned_pending_rows_older_than_a_week(): void {
$GLOBALS['wpdb'] = new class() {
public string $prefix = 'wp_';
public array $queries = array();
public function prepare( string $q, ...$args ): string { return vsprintf( str_replace( '%s', "'%s'", $q ), $args ); }
public function query( string $q ): int { $this->queries[] = $q; return 3; }
};
$before = time();
$n = Maintenance::purge_abandoned();
$sql = $GLOBALS['wpdb']->queries[0] ?? '';
$this->assertSame( 3, $n );
$this->assertStringStartsWith( 'DELETE FROM wp_sg_donations', $sql );
$this->assertStringContainsString( "status = 'pending'", $sql, 'completed donations must never be deleted' );
$this->assertStringContainsString( "paypal_capture_id IS NULL OR paypal_capture_id = ''", $sql, 'anything with a PayPal capture must be kept' );
$this->assertStringContainsString( 'goal_id > 0', $sql, 'test donations (goal_id 0) are handled separately and kept' );
$this->assertMatchesRegularExpression( "/created_at < '(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'/", $sql );
preg_match( "/created_at < '([^']+)'/", $sql, $m );
$cutoff = strtotime( $m[1] . ' UTC' );
$this->assertEqualsWithDelta( $before - 7 * 86400, $cutoff, 5, 'cutoff must be 7 days ago' );
}
}
+37
View File
@@ -96,6 +96,41 @@ final class OverlayPayloadsTest extends TestCase {
$this->assertSame( Payloads::etag( $g ), Payloads::etag( $g ) );
}
public function test_alert_bonuses_humanized_and_empty_when_none(): void {
$out = Payloads::alerts( array( $this->don( 1, array( 'bonuses' => array( 'big_donation', 'mega-win' ) ) ), $this->don( 2 ) ), 0 );
$this->assertSame( array( 'Big donation', 'Mega win' ), $out['alerts'][0]['bonuses'] );
$this->assertSame( array(), $out['alerts'][1]['bonuses'] );
}
public function test_alert_bonuses_sanitize_hostile_event(): void {
$out = Payloads::alerts( array( $this->don( 1, array( 'bonuses' => array( '<img src=x onerror=alert(1)>', '"><script>', '<>', 42, 'big_donation', 'BIG_DONATION' ) ) ) ), 0 );
$b = $out['alerts'][0]['bonuses'];
$this->assertSame( 'Imgsrcxonerroralert1', $b[0] );
foreach ( $b as $label ) {
$this->assertMatchesRegularExpression( '/^[A-Za-z0-9 ]+$/', $label );
}
$this->assertSame( 1, count( array_keys( $b, 'Big donation', true ) ) ); // deduped
}
public function test_bonuses_do_not_affect_masking_moderation_or_since(): void {
$rows = array(
$this->don( 1, array( 'bonuses' => array( 'big_donation' ) ) ),
$this->don( 2, array( 'is_anonymous' => 1, 'donor_name' => 'Secret Sam', 'bonuses' => array( 'big_donation' ) ) ),
$this->don( 3, array( 'moderation' => 'pending', 'bonuses' => array( 'big_donation' ) ) ),
);
$out = Payloads::alerts( $rows, 1 );
$this->assertSame( array( 2 ), array_column( $out['alerts'], 'id' ) );
$this->assertSame( 'Anonymous', $out['alerts'][0]['name'] );
$this->assertStringNotContainsString( 'Secret Sam', json_encode( $out ) );
$this->assertSame( array(), Payloads::alerts( $rows, null )['alerts'] );
}
public function test_etag_changes_when_bonus_added(): void {
$plain = Payloads::alerts( array( $this->don( 5 ) ), 0 );
$bonus = Payloads::alerts( array( $this->don( 5, array( 'bonuses' => array( 'big_donation' ) ) ) ), 0 );
$this->assertNotSame( Payloads::etag( $plain ), Payloads::etag( $bonus ) );
}
public function test_style_sanitizes(): void {
$s = Style::fromQuery( array( 'theme' => 'bogus', 'accent' => '#FF00AA', 'color' => 'red;}</style>', 'bg' => '11223344',
'font' => 'x;}body{', 'scale' => '99' ) );
@@ -114,6 +149,7 @@ final class OverlayPayloadsTest extends TestCase {
public function raisedMinor( array $goal ): int { return 250; }
public function stateValue( int $goalId, string $key ): ?string { return 'timer_ends_at' === $key ? '2000' : null; }
public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => 4 ); }
public function bonusesFor( array $donationIds ): array { return array( 3 => array( 'big_donation' ) ); }
public function donations( ?int $sinceId, int $limit ): array { return array( array( 'id' => 3, 'base_minor' => 100, 'currency' => 'USD', 'donor_name' => 'Z', 'is_anonymous' => 1, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' ) ); }
};
$svc = new OverlayService( $src );
@@ -121,6 +157,7 @@ final class OverlayPayloadsTest extends TestCase {
$this->assertSame( 2000, $svc->payload( 'timer', 1500 )['ends_at'] );
$this->assertSame( 4, $svc->payload( 'counter', 1 )['value'] );
$this->assertSame( 'Anonymous', $svc->payload( 'alerts', 1, 0 )['alerts'][0]['name'] );
$this->assertSame( array( 'Big donation' ), $svc->payload( 'alerts', 1, 0 )['alerts'][0]['bonuses'] );
$this->assertNull( $svc->payload( 'nope', 1 ) );
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Overlay\OverlayDataSource;
use StreamGoals\Overlay\OverlayService;
use StreamGoals\Overlay\Payloads;
use StreamGoals\Overlay\RecentDonationsSource;
final class OverlayRecentModeTest extends TestCase {
/** @param array<int,array<string,mixed>> $db */
private function svc( array &$db ): OverlayService {
return new OverlayService( new class( $db ) implements OverlayDataSource, RecentDonationsSource {
public function __construct( private array &$db ) {}
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' ) ); }
private function ok(): array {
$r = array_filter( $this->db, static fn( $d ) => 'completed' === $d['status'] && 'approved' === $d['moderation'] );
usort( $r, static fn( $a, $b ) => $a['id'] <=> $b['id'] );
return $r;
}
public function donations( ?int $sinceId, int $limit ): array {
return array_slice( array_values( array_filter( $this->ok(), static fn( $d ) => $d['id'] > (int) $sinceId ) ), 0, $limit );
}
public function recentDonations( int $limit ): array { return array_slice( $this->ok(), -$limit ); }
} );
}
private function row( int $id, array $o = array() ): array {
return $o + array( 'id' => $id, 'base_minor' => 500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0,
'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
}
public function test_recent_returns_approved_ascending_masked_with_bonuses(): void {
$db = array( $this->row( 3 ), $this->row( 1, array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ),
$this->row( 2, array( 'moderation' => 'pending' ) ), $this->row( 4, array( 'moderation' => 'rejected' ) ) );
$out = $this->svc( $db )->payload( 'alerts', 1, null, true );
$this->assertSame( array( 1, 3 ), array_column( $out['alerts'], 'id' ) );
$this->assertSame( 3, $out['last_id'] );
$this->assertSame( 'Anonymous', $out['alerts'][0]['name'] );
$this->assertStringNotContainsString( 'Secret', json_encode( $out ) );
$this->assertSame( array( 'Big donation' ), $out['alerts'][1]['bonuses'] );
}
public function test_recent_caps_at_newest_20(): void {
$db = array();
for ( $i = 1; $i <= 25; $i++ ) {
$db[] = $this->row( $i );
}
$out = $this->svc( $db )->payload( 'alerts', 1, null, true );
$this->assertCount( 20, $out['alerts'] );
$this->assertSame( 6, $out['alerts'][0]['id'] );
$this->assertSame( 25, $out['alerts'][19]['id'] );
$this->assertCount( 20, Payloads::alerts( $db, null, 20, true )['alerts'] );
}
public function test_late_approval_appears_in_recent_but_not_since(): void {
$db = array( $this->row( 1 ), $this->row( 2, array( 'moderation' => 'pending' ) ), $this->row( 3 ) );
$svc = $this->svc( $db );
$first = $svc->payload( 'alerts', 1, null, true );
$this->assertSame( array( 1, 3 ), array_column( $first['alerts'], 'id' ) );
$db[1]['moderation'] = 'approved';
$this->assertSame( array(), $svc->payload( 'alerts', 1, $first['last_id'] )['alerts'] ); // old cursor misses it
$next = $svc->payload( 'alerts', 1, null, true );
$this->assertSame( array( 1, 2, 3 ), array_column( $next['alerts'], 'id' ) );
}
public function test_recent_etag_stable_then_changes(): void {
$db = array( $this->row( 1 ), $this->row( 2, array( 'moderation' => 'pending' ) ) );
$s = $this->svc( $db );
$a = Payloads::etag( $s->payload( 'alerts', 1, null, true ) );
$this->assertSame( $a, Payloads::etag( $s->payload( 'alerts', 99, null, true ) ) );
$db[1]['moderation'] = 'approved';
$this->assertNotSame( $a, Payloads::etag( $s->payload( 'alerts', 1, null, true ) ) );
}
}