diff --git a/assets/overlay/overlay.css b/assets/overlay/overlay.css index a578078..fbc82bd 100644 --- a/assets/overlay/overlay.css +++ b/assets/overlay/overlay.css @@ -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)}} diff --git a/assets/overlay/overlay.js b/assets/overlay/overlay.js index 13b67bf..2d2f1f3 100644 --- a/assets/overlay/overlay.js +++ b/assets/overlay/overlay.js @@ -108,6 +108,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 () { diff --git a/includes/Overlay/OverlayDataSource.php b/includes/Overlay/OverlayDataSource.php index cfcb18f..f40fcd1 100644 --- a/includes/Overlay/OverlayDataSource.php +++ b/includes/Overlay/OverlayDataSource.php @@ -28,4 +28,13 @@ interface OverlayDataSource { * @return array> */ 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 donation id => event names + */ + public function bonusesFor( array $donationIds ): array; } diff --git a/includes/Overlay/OverlayService.php b/includes/Overlay/OverlayService.php index 7a213c3..3b96cf3 100644 --- a/includes/Overlay/OverlayService.php +++ b/includes/Overlay/OverlayService.php @@ -26,7 +26,13 @@ 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 ); + $rows = $this->source->donations( $since, 20 ); + $ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) ); + $bonuses = ( 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 ); } return null; } diff --git a/includes/Overlay/Payloads.php b/includes/Overlay/Payloads.php index 1449f38..bfe0b8d 100644 --- a/includes/Overlay/Payloads.php +++ b/includes/Overlay/Payloads.php @@ -107,6 +107,7 @@ final class Payloads { 'amount_display' => self::money( (int) $r['base_minor'], $cur ), 'currency' => $cur, 'message' => (string) ( $r['message'] ?? '' ), + 'bonuses' => self::bonuses( $r['bonuses'] ?? array() ), ); } $alerts = array_slice( $alerts, 0, max( 1, $limit ) ); @@ -116,6 +117,35 @@ final class Payloads { return array( 'alerts' => $alerts, 'last_id' => $lastId ); } + /** + * 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'] ); diff --git a/includes/Overlay/WpdbDataSource.php b/includes/Overlay/WpdbDataSource.php index 234728c..83650f2 100644 --- a/includes/Overlay/WpdbDataSource.php +++ b/includes/Overlay/WpdbDataSource.php @@ -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'; diff --git a/includes/Rules/Engine.php b/includes/Rules/Engine.php index 0ec966b..f741f2f 100644 --- a/includes/Rules/Engine.php +++ b/includes/Rules/Engine.php @@ -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 ); } /** diff --git a/tests/Unit/EngineToOverlayIntegrationTest.php b/tests/Unit/EngineToOverlayIntegrationTest.php index 51671ce..4f1c94b 100644 --- a/tests/Unit/EngineToOverlayIntegrationTest.php +++ b/tests/Unit/EngineToOverlayIntegrationTest.php @@ -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] ); + } } diff --git a/tests/Unit/OverlayPayloadsTest.php b/tests/Unit/OverlayPayloadsTest.php index 1a3262d..d234911 100644 --- a/tests/Unit/OverlayPayloadsTest.php +++ b/tests/Unit/OverlayPayloadsTest.php @@ -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( '', '">