Add donation actions (rewards): menu editor + queue, donate-form buttons, overlay menu widget, alert lines
Test and Release / test (push) Successful in 1m43s
Test and Release / release (push) Successful in 7s

- Actions\Matcher (exact / every), ActionRepository, Recorder (idempotent via unique key)
- Admin: Rewards screen with live preview, queue with Mark done, menu badge
- Donate form shows actions as payment buttons; overlay 'actions' widget; alerts list triggered actions
- Installer DB_VERSION 2 (sg_actions, sg_action_events)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-15 12:36:28 -08:00
1 parent c62ac06b27
commit b0b5012698
25 files changed
+1227 -7

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
/* StreamGoals rewards editor: live plain-English preview of what a donation would trigger. */
( function () {
'use strict';
var dataEl = document.getElementById( 'sg-actions-data' );
var form = document.querySelector( '.sg-action-form' );
var out = document.getElementById( 'sg-action-preview' );
var tryEl = document.getElementById( 'sg-action-try' );
if ( ! dataEl || ! form || ! out || ! tryEl ) { return; }
var cfg = { currency: 'USD', exp: 2, actions: [] };
try { cfg = JSON.parse( dataEl.textContent ); } catch ( e ) { /* keep defaults */ }
function toMinor( raw ) {
var s = String( raw == null ? '' : raw ).replace( /[,\s$€£¥]/g, '' );
var m = /^(\d+)(?:\.(\d+))?$/.exec( s );
if ( ! m ) { return null; }
var frac = m[ 2 ] || '';
if ( frac.length > cfg.exp ) { return null; }
while ( frac.length < cfg.exp ) { frac += '0'; }
var n = parseInt( m[ 1 ] + frac, 10 );
return isFinite( n ) ? n : null;
}
function money( minor ) {
var s = String( minor );
if ( cfg.exp === 0 ) { return cfg.currency + ' ' + s; }
while ( s.length <= cfg.exp ) { s = '0' + s; }
return cfg.currency + ' ' + s.slice( 0, -cfg.exp ) + '.' + s.slice( -cfg.exp );
}
function current() {
var mode = form.querySelector( 'input[name="mode"]:checked' );
return {
id: cfg.editId || -1,
goal_id: parseInt( form.elements.goal_id.value, 10 ) || 0,
title: form.elements.title.value.trim() || 'This reward',
amount_minor: toMinor( form.elements.amount.value ) || 0,
mode: mode ? mode.value : 'exact'
};
}
function match( base, list ) {
var res = [];
if ( base <= 0 ) { return res; }
list.forEach( function ( a ) {
if ( a.amount_minor <= 0 ) { return; }
var times = a.mode === 'every' ? Math.floor( base / a.amount_minor ) : ( base === a.amount_minor ? 1 : 0 );
if ( times >= 1 ) { res.push( a.title + ' x' + times ); }
} );
return res;
}
function render() {
var base = toMinor( tryEl.value );
if ( base === null || base <= 0 ) { out.textContent = 'Type a donation amount to see which rewards it would trigger.'; return; }
var me = current();
var list = cfg.actions.filter( function ( a ) { return a.goal_id === 0 || me.goal_id === 0 || a.goal_id === me.goal_id; } );
list.push( me );
var hits = match( base, list );
out.textContent = hits.length ? 'A ' + money( base ) + ' donation will trigger: ' + hits.join( ', ' ) : 'A ' + money( base ) + ' donation will not trigger any reward.';
}
form.addEventListener( 'input', render );
form.addEventListener( 'change', render );
var amt = form.elements.amount.value;
if ( amt && ! tryEl.value ) { tryEl.value = amt; }
render();
}() );
+5
View File
@@ -17,3 +17,8 @@
.sg-donate .sg-info{flex:none;width:1.4rem;height:1.4rem;padding:0;border-radius:50%;border:1.5px solid currentColor;background:transparent;color:inherit;font:italic 700 .85rem/1 Georgia,serif;cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
.sg-donate .sg-info:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.sg-donate .sg-tip{margin-top:.4rem;padding:.6rem .75rem;border:1px solid rgba(128,128,128,.5);border-radius:.4rem;font-size:.9em;line-height:1.4}
.sg-donate .sg-presets.sg-actions{flex-direction:column;flex-wrap:nowrap;align-items:stretch}
.sg-donate .sg-presets button.sg-action{display:flex;flex-direction:column;align-items:flex-start;gap:.15rem;width:100%;text-align:left;padding:.55rem .75rem;min-height:2.75rem;box-sizing:border-box;overflow-wrap:anywhere}
.sg-donate .sg-act-title{font-weight:600}
.sg-donate .sg-act-desc{font-size:.85em;font-weight:400;opacity:.8}
.sg-donate .sg-presets button.sg-action:focus-visible{outline:2px solid currentColor;outline-offset:2px}
+33
View File
@@ -115,9 +115,34 @@
function anonNow() { return anon.checked; }
anon.addEventListener('change', function () { nameRow.hidden = anon.checked || C.policy === 'force_anonymous'; });
// Actions (rewards) for the selected goal, minus any below the minimum. They replace the generic presets.
function goalActions() {
return (state.goal.actions || []).filter(function (a) {
return a && a.amount_minor > 0 && a.amount_minor >= (C.minMinor || 0);
});
}
function minorToStr(minor, exp) { return (minor / Math.pow(10, exp)).toFixed(exp); }
function amountMinorNow() {
var typed = parseFloat(amountStr());
return isFinite(typed) ? Math.round(typed * Math.pow(10, state.goal.exp)) : -1;
}
function buildPresets() {
presetBox.textContent = '';
hint.textContent = sprintf1(T.minHint, fmt(C.minMinor || 0, state.goal.exp, state.goal.currency));
var acts = goalActions();
presetBox.className = 'sg-presets' + (acts.length ? ' sg-actions' : '');
if (acts.length) {
acts.forEach(function (a) {
var money = fmt(a.amount_minor, state.goal.exp, state.goal.currency);
var lead = a.mode === 'every' ? sprintf1(T.everyLabel || 'Every %s', money) : money;
var kids = [el('span', { 'class': 'sg-act-title', text: lead + ': ' + a.title })];
if (a.description) { kids.push(el('span', { 'class': 'sg-act-desc', text: a.description })); }
var b = el('button', { type: 'button', 'class': 'sg-action', 'aria-pressed': 'false' }, kids);
b.addEventListener('click', function () { amount.value = minorToStr(a.amount_minor, state.goal.exp); refresh(); });
presetBox.appendChild(b);
});
return;
}
presets(state.goal.exp).forEach(function (p) {
var b = el('button', { type: 'button', 'aria-pressed': 'false', text: fmt(state.goal.exp === 0 ? p : p * 100, state.goal.exp, state.goal.currency) });
b.addEventListener('click', function () { amount.value = String(p); refresh(); });
@@ -125,6 +150,14 @@
});
}
function markPresets() {
var acts = goalActions();
if (acts.length) {
var now = amountMinorNow();
Array.prototype.forEach.call(presetBox.children, function (b, i) {
b.setAttribute('aria-pressed', String(!!acts[i] && acts[i].amount_minor === now));
});
return;
}
var cur = amountStr();
Array.prototype.forEach.call(presetBox.children, function (b, i) {
b.setAttribute('aria-pressed', String(String(presets(state.goal.exp)[i]) === cur));
+11
View File
@@ -36,3 +36,14 @@ body.sg-offline #sg-root{opacity:.6}
@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,.sg-alert.sg-bonus,.sg-alert.sg-bonus.sg-out{animation:none}.sg-alert.sg-bonus{box-shadow:0 0 .8em var(--sg-accent2)}}
.sg-w-actions #sg-root{align-items:flex-start}
.sg-w-actions #sg-root:empty{display:none}
.sg-menu{height:100%;display:flex;flex-direction:column;overflow:hidden}
.sg-menu-view{flex:1;min-height:0;overflow:hidden}
.sg-menu-list{list-style:none;margin:0;padding:0}
.sg-menu-item{padding:.3em 0;font-weight:600;overflow-wrap:anywhere}
.sg-menu-item b{color:var(--sg-accent2);font-weight:800}
.sg-menu-desc{display:block;font-size:.75em;font-weight:400;opacity:.8}
.sg-menu-track.sg-scrolling{animation:sg-scroll var(--sg-scroll-s,20s) linear infinite}
@keyframes sg-scroll{from{transform:translateY(0)}to{transform:translateY(-50%)}}
@media (prefers-reduced-motion:reduce){.sg-menu-track.sg-scrolling{animation:none}}
+45
View File
@@ -131,6 +131,12 @@
card.appendChild(el('div', 'sg-bonus-line', 'BONUS: ' + String(bonuses[j]) + '!'));
}
}
var acts = Array.isArray(a.actions) ? a.actions : [];
if (acts.length) card.classList.add('sg-bonus');
for (var k = 0; k < acts.length; k++) {
var times = parseInt(acts[k].times, 10) || 1;
card.appendChild(el('div', 'sg-bonus-line', 'ACTION: ' + String(acts[k].title) + (times > 1 ? ' x' + times : '')));
}
if (a.message) card.appendChild(el('div', 'sg-alert-msg', a.message));
root.appendChild(card);
setTimeout(function () {
@@ -139,6 +145,44 @@
}, 6500);
}
// ---- actions (reward menu) ----
// Renders nothing visible when there are no actions. Long lists scroll gently via CSS (--sg-rows sets the duration).
var actionsSig = null;
function renderActions(d) {
var list = Array.isArray(d.actions) ? d.actions : [];
var sig = JSON.stringify(list);
if (sig === actionsSig) return;
actionsSig = sig;
root.textContent = '';
if (!d.active || !list.length) return;
var card = el('div', 'sg-card sg-menu');
var view = el('div', 'sg-menu-view');
var ul = el('ul', 'sg-menu-list');
list.forEach(function (a) {
var li = el('li', 'sg-menu-item');
var lead = (a.mode === 'every' ? 'Every ' : '') + a.amount_display;
li.appendChild(el('b', null, lead));
li.appendChild(document.createTextNode(' \u2014 ' + String(a.title)));
if (a.description) li.appendChild(el('span', 'sg-menu-desc', String(a.description)));
ul.appendChild(li);
});
var track = el('div', 'sg-menu-track');
track.appendChild(ul);
view.appendChild(track);
card.appendChild(view);
root.appendChild(card);
// Overflow check after layout: duplicate the list for a seamless loop and start the CSS scroll.
requestAnimationFrame(function () {
if (ul.scrollHeight > view.clientHeight + 2) {
var dup = ul.cloneNode(true);
dup.setAttribute('aria-hidden', 'true');
track.appendChild(dup);
track.style.setProperty('--sg-scroll-s', Math.max(8, list.length * 3) + 's');
track.classList.add('sg-scrolling');
}
});
}
// ---- polling ----
function url() {
var u = endpoint;
@@ -179,6 +223,7 @@
else if (widget === 'timer') renderTimer(d, now);
else if (widget === 'counter') renderCounter(d);
else if (widget === 'alerts') renderAlerts(d);
else if (widget === 'actions') renderActions(d);
}
if (widget === 'timer') tickTimer();
+155
View File
@@ -0,0 +1,155 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Actions;
/** $wpdb access to sg_actions / sg_action_events. */
final class ActionRepository {
private object $db;
public function __construct( ?object $db = null ) {
$this->db = $db ?? $GLOBALS['wpdb'];
}
private function t( string $name ): string {
return $this->db->prefix . 'sg_' . $name;
}
/** Normalise numeric columns. @return array{id:int,goal_id:int,title:string,description:string,amount_minor:int,mode:string,enabled:int,sort:int,created_at:string} */
private static function cast( array $r ): array {
return array(
'id' => (int) ( $r['id'] ?? 0 ),
'goal_id' => (int) ( $r['goal_id'] ?? 0 ),
'title' => (string) ( $r['title'] ?? '' ),
'description' => (string) ( $r['description'] ?? '' ),
'amount_minor' => (int) ( $r['amount_minor'] ?? 0 ),
'mode' => (string) ( $r['mode'] ?? 'exact' ),
'enabled' => (int) ( $r['enabled'] ?? 0 ),
'sort' => (int) ( $r['sort'] ?? 0 ),
'created_at' => (string) ( $r['created_at'] ?? '' ),
);
}
/** Enabled actions for a goal (goal_id IN (0,$goalId)) ordered by sort, amount. */
public function enabledForGoal( int $goalId ): array {
$rows = $this->db->get_results(
$this->db->prepare( 'SELECT * FROM ' . $this->t( 'actions' ) . ' WHERE enabled = 1 AND goal_id IN (0, %d) ORDER BY sort ASC, amount_minor ASC, id ASC', $goalId ),
ARRAY_A
);
return array_map( array( self::class, 'cast' ), (array) $rows );
}
/** All actions (enabled or not) for the admin list. */
public function all(): array {
$rows = $this->db->get_results( 'SELECT * FROM ' . $this->t( 'actions' ) . ' ORDER BY sort ASC, amount_minor ASC, id ASC', ARRAY_A );
return array_map( array( self::class, 'cast' ), (array) $rows );
}
public function find( int $id ): ?array {
$row = $this->db->get_row( $this->db->prepare( 'SELECT * FROM ' . $this->t( 'actions' ) . ' WHERE id = %d', $id ), ARRAY_A );
return $row ? self::cast( $row ) : null;
}
public function nextSort(): int {
return (int) $this->db->get_var( 'SELECT COALESCE(MAX(sort),0)+10 FROM ' . $this->t( 'actions' ) );
}
/** @param array{goal_id:int,title:string,description:string,amount_minor:int,mode:string,sort:int} $d @return int new id (0 on failure) */
public function create( array $d ): int {
$ok = $this->db->insert(
$this->t( 'actions' ),
array(
'goal_id' => (int) $d['goal_id'],
'title' => (string) $d['title'],
'description' => (string) $d['description'],
'amount_minor' => (int) $d['amount_minor'],
'mode' => (string) $d['mode'],
'enabled' => 1,
'sort' => (int) $d['sort'],
'created_at' => gmdate( 'Y-m-d H:i:s' ),
),
array( '%d', '%s', '%s', '%d', '%s', '%d', '%d', '%s' )
);
return $ok ? (int) $this->db->insert_id : 0;
}
public function update( int $id, array $d ): void {
$this->db->update(
$this->t( 'actions' ),
array(
'goal_id' => (int) $d['goal_id'],
'title' => (string) $d['title'],
'description' => (string) $d['description'],
'amount_minor' => (int) $d['amount_minor'],
'mode' => (string) $d['mode'],
'sort' => (int) $d['sort'],
),
array( 'id' => $id ),
array( '%d', '%s', '%s', '%d', '%s', '%d' ),
array( '%d' )
);
}
public function setEnabled( int $id, bool $on ): void {
$this->db->update( $this->t( 'actions' ), array( 'enabled' => $on ? 1 : 0 ), array( 'id' => $id ), array( '%d' ), array( '%d' ) );
}
/** Past events keep their title snapshot, so history survives. */
public function delete( int $id ): void {
$this->db->delete( $this->t( 'actions' ), array( 'id' => $id ), array( '%d' ) );
}
/**
* Queue triggered actions for a donation. INSERT IGNORE + UNIQUE(donation_id, action_id): replays do nothing.
*
* @param array[] $matches Output of Matcher::match().
*/
public function recordEvents( int $donationId, array $matches ): void {
$now = gmdate( 'Y-m-d H:i:s' );
foreach ( $matches as $m ) {
$times = (int) ( $m['times'] ?? 0 );
$aid = (int) ( $m['action_id'] ?? 0 );
if ( $donationId <= 0 || $aid <= 0 || $times < 1 ) {
continue;
}
$title = function_exists( 'mb_substr' ) ? mb_substr( (string) ( $m['title'] ?? '' ), 0, 120 ) : substr( (string) ( $m['title'] ?? '' ), 0, 120 );
$this->db->query(
$this->db->prepare(
'INSERT IGNORE INTO ' . $this->t( 'action_events' ) . " (donation_id, action_id, times, title, status, created_at) VALUES (%d, %d, %d, %s, 'queued', %s)",
$donationId,
$aid,
$times,
$title,
$now
)
);
}
}
private function eventSelect(): string {
return 'SELECT e.*, d.donor_name, d.is_anonymous, d.message, d.base_minor, d.currency FROM ' . $this->t( 'action_events' ) . ' e LEFT JOIN ' . $this->t( 'donations' ) . ' d ON d.id = e.donation_id';
}
/** Oldest first. Rows include donor_name, is_anonymous, message, base_minor, currency from the donation. */
public function queued( int $limit ): array {
return (array) $this->db->get_results( $this->db->prepare( $this->eventSelect() . " WHERE e.status = 'queued' ORDER BY e.id ASC LIMIT %d", $limit ), ARRAY_A );
}
public function recentDone( int $limit ): array {
return (array) $this->db->get_results( $this->db->prepare( $this->eventSelect() . " WHERE e.status = 'done' ORDER BY e.done_at DESC, e.id DESC LIMIT %d", $limit ), ARRAY_A );
}
public function queuedCount(): int {
return (int) $this->db->get_var( 'SELECT COUNT(*) FROM ' . $this->t( 'action_events' ) . " WHERE status = 'queued'" );
}
public function markDone( int $eventId ): bool {
$n = $this->db->query( $this->db->prepare( 'UPDATE ' . $this->t( 'action_events' ) . " SET status = 'done', done_at = %s WHERE id = %d AND status = 'queued'", gmdate( 'Y-m-d H:i:s' ), $eventId ) );
return 1 === (int) $n;
}
public function markAllDone(): int {
return (int) $this->db->query( $this->db->prepare( 'UPDATE ' . $this->t( 'action_events' ) . " SET status = 'done', done_at = %s WHERE status = 'queued'", gmdate( 'Y-m-d H:i:s' ) ) );
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Actions;
/** Pure: which actions does a donation of $baseMinor trigger, and how many times each. */
final class Matcher {
public const EXACT = 'exact';
public const EVERY = 'every';
/**
* @param array[] $actions Rows with keys id, title, amount_minor, mode. Malformed rows are skipped.
* @return array<int,array{action_id:int,title:string,times:int}> In the order of $actions.
*/
public static function match( int $baseMinor, array $actions ): array {
$out = array();
if ( $baseMinor <= 0 ) {
return $out;
}
foreach ( $actions as $a ) {
if ( ! is_array( $a ) || ! isset( $a['id'], $a['amount_minor'], $a['mode'], $a['title'] ) ) {
continue;
}
if ( ! is_numeric( $a['id'] ) || ! is_numeric( $a['amount_minor'] ) || ! is_string( $a['mode'] ) || ! is_scalar( $a['title'] ) ) {
continue;
}
$id = (int) $a['id'];
$amount = (int) $a['amount_minor'];
if ( $id <= 0 || $amount <= 0 ) {
continue;
}
if ( self::EXACT === $a['mode'] ) {
$times = $baseMinor === $amount ? 1 : 0;
} elseif ( self::EVERY === $a['mode'] ) {
$times = intdiv( $baseMinor, $amount );
} else {
continue;
}
if ( $times >= 1 ) {
$out[] = array( 'action_id' => $id, 'title' => (string) $a['title'], 'times' => $times );
}
}
return $out;
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare( strict_types=1 );
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 {
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;
}
$repo = new ActionRepository( $wpdb );
$matches = Matcher::match( (int) $row['base_minor'], $repo->enabledForGoal( (int) $row['goal_id'] ) );
if ( $matches ) {
$repo->recordEvents( $donationId, $matches );
}
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: Recorder failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
}
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Admin;
use StreamGoals\Actions\Matcher;
/** Pure validation/sanitizing for the rewards form. */
final class ActionInput {
/**
* @param int[] $validGoalIds Existing goal ids (0 = all goals is always allowed).
* @return array{data:?array,error:?string}
*/
public static function validate( array $post, int $minMinor, string $currency, array $validGoalIds, ?int $defaultSort = null ): array {
$fail = static fn( string $m ): array => array( 'data' => null, 'error' => $m );
$title = Input::text( $post['title'] ?? '', 200 );
if ( '' === $title ) {
return $fail( 'Please give the reward a title, for example "Eat a bean".' );
}
if ( self::len( $title ) > 120 ) {
return $fail( 'The title can be at most 120 characters.' );
}
$desc = Input::text( $post['description'] ?? '', 400 );
if ( self::len( $desc ) > 255 ) {
return $fail( 'The description can be at most 255 characters.' );
}
$amount = Input::amountToMinor( $post['amount'] ?? '', $currency );
if ( null === $amount || $amount <= 0 ) {
return $fail( 'Please enter an amount greater than zero, for example 5.00.' );
}
if ( $amount < $minMinor ) {
return $fail( 'The amount must be at least the minimum donation (' . Format::money( $minMinor, $currency ) . ').' );
}
$mode = is_scalar( $post['mode'] ?? null ) ? (string) $post['mode'] : '';
if ( ! in_array( $mode, array( Matcher::EXACT, Matcher::EVERY ), true ) ) {
return $fail( 'Please choose when the reward triggers.' );
}
$goalRaw = $post['goal_id'] ?? '0';
$goal = Input::int( $goalRaw, 0, PHP_INT_MAX >> 1 );
if ( null === $goal || ( 0 !== $goal && ! in_array( $goal, array_map( 'intval', $validGoalIds ), true ) ) ) {
return $fail( 'Please choose all goals or one of your goals.' );
}
$sortRaw = $post['sort'] ?? '';
$sort = ( is_scalar( $sortRaw ) && '' === trim( (string) $sortRaw ) ) ? ( $defaultSort ?? 0 ) : Input::int( $sortRaw, 0, 99999 );
if ( null === $sort ) {
return $fail( 'The sort order must be a whole number from 0 to 99999.' );
}
return array(
'data' => array( 'goal_id' => $goal, 'title' => $title, 'description' => $desc, 'amount_minor' => $amount, 'mode' => $mode, 'sort' => $sort ),
'error' => null,
);
}
private static function len( string $s ): int {
return function_exists( 'mb_strlen' ) ? mb_strlen( $s ) : strlen( $s );
}
}
+219
View File
@@ -0,0 +1,219 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Admin;
use StreamGoals\Actions\ActionRepository;
use StreamGoals\Actions\Matcher;
use StreamGoals\Core\Money;
use StreamGoals\Core\Settings;
/** "Rewards": the menu of on-stream actions, and the queue of triggered ones. */
final class ActionsPage {
public const PAGE = 'streamgoals-rewards';
private static function repo(): ActionRepository {
return new ActionRepository();
}
public static function minMinor(): int {
return Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
}
public static function queuedCount(): int {
try {
return self::repo()->queuedCount();
} catch ( \Throwable ) {
return 0;
}
}
private static function url( array $args = array() ): string {
return Admin::url( self::PAGE, $args );
}
/* ---------------------------------------------------------------- render */
public static function render(): void {
Admin::open( 'Rewards' );
$edit = Admin::get_int( 'edit' );
if ( 'new' === Admin::get_str( 'view' ) || $edit ) {
self::renderForm( $edit );
} else {
self::renderQueue();
self::renderMenu();
}
Admin::close();
}
private static function renderQueue(): void {
$cur = Admin::currency();
$repo = self::repo();
$queued = $repo->queued( 200 );
echo '<div class="sg-card"><h2>Waiting to be done (' . count( $queued ) . ')</h2>';
if ( ! $queued ) {
echo '<p>Nothing in the queue. When a donation triggers a reward, it shows up here.</p>';
} else {
echo '<table class="widefat striped sg-table"><thead><tr><th>Donor</th><th>Amount</th><th>Reward</th><th>Time</th><th>Message</th><th></th></tr></thead><tbody>';
foreach ( $queued as $e ) {
echo '<tr><td>' . esc_html( Format::donorName( $e ) ) . '</td>';
echo '<td>' . esc_html( Format::money( (int) ( $e['base_minor'] ?? 0 ), Format::currency( $e['currency'] ?? $cur ) ) ) . '</td>';
echo '<td><strong>' . esc_html( (string) $e['title'] ) . '</strong> &times; ' . (int) $e['times'] . '</td>';
echo '<td>' . esc_html( self::when( (string) $e['created_at'] ) ) . '</td>';
echo '<td>' . esc_html( (string) ( $e['message'] ?? '' ) ) . '</td><td>';
Admin::form( 'sg_event_done', array( 'event_id' => (int) $e['id'] ), 'sg-inline' );
echo '<button class="button button-primary">Mark done</button></form></td></tr>';
}
echo '</tbody></table>';
Admin::form( 'sg_event_done_all' );
echo '<p><button class="button">Mark all done</button></p></form>';
}
$done = $repo->recentDone( 15 );
if ( $done ) {
echo '<h3>Recently done</h3><ul class="sg-preview-list">';
foreach ( $done as $e ) {
echo '<li>' . esc_html( Format::donorName( $e ) . ': ' . $e['title'] . ' x ' . (int) $e['times'] . ' (' . self::when( (string) ( $e['done_at'] ?? '' ) ) . ')' ) . '</li>';
}
echo '</ul>';
}
echo '</div>';
}
private static function when( string $utc ): string {
return '' === $utc ? '' : get_date_from_gmt( $utc, 'Y-m-d H:i' );
}
/** @return array<int,string> goal id => title */
private static function goalTitles(): array {
$out = array();
foreach ( Store::goals()->all() as $g ) {
$out[ (int) $g['id'] ] = (string) $g['title'];
}
return $out;
}
private static function renderMenu(): void {
$cur = Admin::currency();
$actions = self::repo()->all();
$goals = self::goalTitles();
echo '<div class="sg-card"><h2>Your reward menu</h2>';
echo '<p class="description">Donors pick a reward on the donation form (or just donate the amount). Rewards must be at least ' . esc_html( Format::money( self::minMinor(), $cur ) ) . ', the minimum donation.</p>';
echo '<p><a class="button button-primary" href="' . esc_url( self::url( array( 'view' => 'new' ) ) ) . '">Add a reward</a></p>';
if ( ! $actions ) {
echo '<p>No rewards yet.</p></div>';
return;
}
echo '<table class="widefat striped sg-table"><thead><tr><th>Reward</th><th>Amount</th><th>Triggers</th><th>Applies to</th><th>Order</th><th>Actions</th></tr></thead><tbody>';
foreach ( $actions as $a ) {
$id = (int) $a['id'];
echo '<tr' . ( $a['enabled'] ? '' : ' class="sg-off"' ) . '><td><strong>' . esc_html( $a['title'] ) . '</strong>';
if ( '' !== $a['description'] ) {
echo '<br><span class="description">' . esc_html( $a['description'] ) . '</span>';
}
echo '</td><td>' . esc_html( Format::money( $a['amount_minor'], $cur ) ) . '</td>';
echo '<td>' . esc_html( Matcher::EVERY === $a['mode'] ? 'Every time it adds up' : 'Exactly this amount' ) . '</td>';
echo '<td>' . esc_html( 0 === $a['goal_id'] ? 'All goals' : ( $goals[ $a['goal_id'] ] ?? 'Goal #' . $a['goal_id'] ) ) . '</td>';
echo '<td>' . (int) $a['sort'] . '</td><td class="sg-actions">';
echo '<a class="button" href="' . esc_url( self::url( array( 'edit' => $id ) ) ) . '">Edit</a> ';
Admin::form( 'sg_action_toggle', array( 'action_id' => $id, 'enabled' => $a['enabled'] ? 0 : 1 ), 'sg-inline' );
echo '<button class="button">' . ( $a['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
Admin::form( 'sg_action_delete', array( 'action_id' => $id ), 'sg-inline sg-confirm' );
echo '<button class="button button-link-delete" data-confirm="Delete this reward? Rewards already waiting in the queue stay there.">Delete</button></form>';
echo '</td></tr>';
}
echo '</tbody></table></div>';
}
private static function renderForm( int $id ): void {
$a = $id ? self::repo()->find( $id ) : null;
if ( $id && ! $a ) {
echo '<p>That reward no longer exists. <a href="' . esc_url( self::url() ) . '">Back to rewards</a></p>';
return;
}
$cur = Admin::currency();
$goals = self::goalTitles();
$val = static fn( string $k, $d = '' ) => $a[ $k ] ?? $d;
$mode = (string) $val( 'mode', Matcher::EXACT );
$data = array(
'currency' => $cur,
'exp' => Money::exponent( $cur ),
'editId' => $id,
'actions' => array_values( array_map(
static fn( array $r ): array => array( 'id' => $r['id'], 'goal_id' => $r['goal_id'], 'title' => $r['title'], 'amount_minor' => $r['amount_minor'], 'mode' => $r['mode'] ),
array_filter( self::repo()->all(), static fn( array $r ): bool => (bool) $r['enabled'] && $r['id'] !== $id )
) ),
);
echo '<h2>' . ( $a ? 'Edit reward' : 'Add a reward' ) . '</h2>';
Admin::form( 'sg_action_save', array( 'action_id' => $id ), 'sg-action-form' );
echo '<table class="form-table" role="presentation">';
echo '<tr><th scope="row"><label for="sg_a_title">Title</label></th><td><input type="text" required maxlength="120" id="sg_a_title" name="title" class="regular-text" value="' . esc_attr( (string) $val( 'title' ) ) . '"><p class="description">What you do on stream, for example "Eat a bean". Up to 120 characters.</p></td></tr>';
echo '<tr><th scope="row"><label for="sg_a_desc">Description</label></th><td><input type="text" maxlength="255" id="sg_a_desc" name="description" class="large-text" value="' . esc_attr( (string) $val( 'description' ) ) . '"><p class="description">Optional. A short note shown to donors.</p></td></tr>';
echo '<tr><th scope="row"><label for="sg_a_amount">Amount (' . esc_html( $cur ) . ')</label></th><td><input type="text" required inputmode="decimal" id="sg_a_amount" name="amount" class="small-text" value="' . esc_attr( $a ? Format::decimal( (int) $a['amount_minor'], $cur ) : '' ) . '"><p class="description">At least ' . esc_html( Format::money( self::minMinor(), $cur ) ) . ' (your minimum donation). The amount before any fee the donor chooses to cover.</p></td></tr>';
echo '<tr><th scope="row"><label for="sg_a_goal">Applies to</label></th><td><select id="sg_a_goal" name="goal_id"><option value="0"' . selected( (int) $val( 'goal_id', 0 ), 0, false ) . '>All goals</option>';
foreach ( $goals as $gid => $title ) {
echo '<option value="' . (int) $gid . '"' . selected( (int) $val( 'goal_id', 0 ), $gid, false ) . '>' . esc_html( $title ) . '</option>';
}
echo '</select></td></tr>';
echo '<tr><th scope="row">Triggers</th><td>';
echo '<label><input type="radio" name="mode" value="exact"' . checked( $mode, Matcher::EXACT, false ) . '> Exactly this amount</label><br>';
echo '<label><input type="radio" name="mode" value="every"' . checked( $mode, Matcher::EVERY, false ) . '> Every time the donation adds up to this amount (a $10 donation triggers a $5 reward twice)</label></td></tr>';
echo '<tr><th scope="row"><label for="sg_a_sort">Order</label></th><td><input type="number" min="0" max="99999" id="sg_a_sort" name="sort" class="small-text" value="' . ( $a ? (int) $a['sort'] : '' ) . '"><p class="description">Lower numbers are listed first. Leave empty to put it last.</p></td></tr>';
echo '</table>';
echo '<div class="sg-card"><h3>What would a donation do?</h3><label>Donation amount (' . esc_html( $cur ) . ') <input type="text" id="sg-action-try" class="small-text" inputmode="decimal"></label>';
echo '<p id="sg-action-preview" class="sg-form-preview" aria-live="polite"></p>';
echo '<script type="application/json" id="sg-actions-data">' . wp_json_encode( $data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . '</script></div>';
echo '<p><button class="button button-primary">' . ( $a ? 'Save reward' : 'Add reward' ) . '</button> <a class="button" href="' . esc_url( self::url() ) . '">Cancel</a></p></form>';
}
/* -------------------------------------------------------------- handlers */
public static function handleSave(): void {
Admin::guard( 'sg_action_save' );
$post = Admin::post_raw();
$id = isset( $post['action_id'] ) ? absint( $post['action_id'] ) : 0;
$back = self::url( $id ? array( 'edit' => $id ) : array( 'view' => 'new' ) );
$repo = self::repo();
if ( $id && ! $repo->find( $id ) ) {
Admin::redirect( self::url(), 'error', 'That reward no longer exists.' );
}
$res = ActionInput::validate( $post, self::minMinor(), Admin::currency(), array_keys( self::goalTitles() ), $repo->nextSort() );
if ( null === $res['data'] ) {
Admin::redirect( $back, 'error', (string) $res['error'] );
}
if ( $id ) {
$repo->update( $id, $res['data'] );
} else {
$repo->create( $res['data'] );
}
Admin::redirect( self::url(), 'success', 'Reward saved.' );
}
public static function handleToggle(): void {
Admin::guard( 'sg_action_toggle' );
$post = Admin::post_raw();
self::repo()->setEnabled( isset( $post['action_id'] ) ? absint( $post['action_id'] ) : 0, ! empty( $post['enabled'] ) );
Admin::redirect( self::url(), 'success', 'Reward updated.' );
}
public static function handleDelete(): void {
Admin::guard( 'sg_action_delete' );
$post = Admin::post_raw();
self::repo()->delete( isset( $post['action_id'] ) ? absint( $post['action_id'] ) : 0 );
Admin::redirect( self::url(), 'success', 'Reward deleted.' );
}
public static function handleDone(): void {
Admin::guard( 'sg_event_done' );
$post = Admin::post_raw();
self::repo()->markDone( isset( $post['event_id'] ) ? absint( $post['event_id'] ) : 0 );
Admin::redirect( self::url(), 'success', 'Marked as done.' );
}
public static function handleDoneAll(): void {
Admin::guard( 'sg_event_done_all' );
$n = self::repo()->markAllDone();
Admin::redirect( self::url(), 'success', $n . ( 1 === $n ? ' reward' : ' rewards' ) . ' marked as done.' );
}
}
+11
View File
@@ -25,6 +25,11 @@ final class Admin {
'sg_rule_save' => array( GoalsPage::class, 'handleRuleSave' ),
'sg_rule_toggle' => array( GoalsPage::class, 'handleRuleToggle' ),
'sg_rule_delete' => array( GoalsPage::class, 'handleRuleDelete' ),
'sg_action_save' => array( ActionsPage::class, 'handleSave' ),
'sg_action_toggle' => array( ActionsPage::class, 'handleToggle' ),
'sg_action_delete' => array( ActionsPage::class, 'handleDelete' ),
'sg_event_done' => array( ActionsPage::class, 'handleDone' ),
'sg_event_done_all' => array( ActionsPage::class, 'handleDoneAll' ),
'sg_export_csv' => array( DonationsPage::class, 'handleExport' ),
'sg_moderate' => array( DonationsPage::class, 'handleModerate' ),
'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ),
@@ -57,6 +62,9 @@ final class Admin {
$badge = $pending > 0 ? ' <span class="awaiting-mod">' . (int) $pending . '</span>' : '';
add_submenu_page( self::HOME, 'Moderation', 'Moderation' . $badge, self::CAP, 'streamgoals-moderation', array( DonationsPage::class, 'renderModeration' ) );
}
$queued = ActionsPage::queuedCount();
$qbadge = $queued > 0 ? ' <span class="awaiting-mod">' . (int) $queued . '</span>' : '';
add_submenu_page( self::HOME, 'Rewards', 'Rewards' . $qbadge, self::CAP, ActionsPage::PAGE, array( ActionsPage::class, 'render' ) );
add_submenu_page( self::HOME, 'Overlays', 'Overlays', self::CAP, 'streamgoals-overlays', array( OverlaysPage::class, 'render' ) );
add_submenu_page( self::HOME, 'Settings', 'Settings', self::CAP, 'streamgoals-settings', array( SettingsPage::class, 'render' ) );
}
@@ -90,6 +98,9 @@ final class Admin {
if ( self::HOME === $page ) {
wp_enqueue_script( 'streamgoals-rules', STREAMGOALS_URL . 'assets/admin/rules.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
}
if ( ActionsPage::PAGE === $page ) {
wp_enqueue_script( 'streamgoals-actions', STREAMGOALS_URL . 'assets/admin/actions.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
}
if ( 'streamgoals-overlays' === $page ) {
wp_enqueue_script( 'streamgoals-overlays', STREAMGOALS_URL . 'assets/admin/overlays.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
}
+1
View File
@@ -15,6 +15,7 @@ final class OverlaysPage {
'timer' => array( 'Subathon timer', 400, 120, 'Countdown that grows with donations (needs an "Add time" rule).' ),
'counter' => array( 'Counter', 400, 120, 'A running count (needs a "Counter" rule).' ),
'alerts' => array( 'Donation alerts', 600, 300, 'Pop-up alert for each new donation.' ),
'actions' => array( 'Rewards menu', 500, 400, 'Lists your donation actions (e.g. "$5: Eat a bean") for the active goal. Shows nothing if you have none.' ),
);
/** @return array{url:string,base:string,sep:string} */
+29 -1
View File
@@ -8,7 +8,7 @@ namespace StreamGoals\Core;
*/
final class Installer {
public const DB_VERSION = '1';
public const DB_VERSION = '2';
public static function activate(): void {
self::install_schema();
@@ -94,6 +94,34 @@ final class Installer {
PRIMARY KEY (goal_id,skey)
) $c;" );
dbDelta( "CREATE TABLE {$p}actions (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
goal_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
title VARCHAR(120) NOT NULL,
description VARCHAR(255) NOT NULL DEFAULT '',
amount_minor BIGINT UNSIGNED NOT NULL,
mode VARCHAR(8) NOT NULL DEFAULT 'exact',
enabled TINYINT(1) NOT NULL DEFAULT 1,
sort INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY goal_enabled (goal_id,enabled)
) $c;" );
dbDelta( "CREATE TABLE {$p}action_events (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
donation_id BIGINT UNSIGNED NOT NULL,
action_id BIGINT UNSIGNED NOT NULL,
times INT NOT NULL DEFAULT 1,
title VARCHAR(120) NOT NULL,
status VARCHAR(8) NOT NULL DEFAULT 'queued',
created_at DATETIME NOT NULL,
done_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY donation_action (donation_id,action_id),
KEY status_id (status,id)
) $c;" );
update_option( 'sg_db_version', self::DB_VERSION );
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
/** Optional capability: donation actions (rewards). Sources without it simply show no actions. */
interface ActionsSource {
/**
* Enabled actions for the goal (goal_id = $goalId or 0), already filtered to the effective minimum and ordered.
* Raw rows with keys title, description, amount_minor, mode.
*
* @return array<int,array<string,mixed>>
*/
public function menuActions( int $goalId ): array;
/**
* Triggered actions per donation (sg_action_events), in trigger order. One lookup for the whole page.
* Raw rows with keys title, times; Payloads sanitizes them.
*
* @param int[] $donationIds
* @return array<int,array<int,array<string,mixed>>> donation id => events
*/
public function actionsFor( array $donationIds ): array;
}
+6 -1
View File
@@ -6,7 +6,7 @@ namespace StreamGoals\Overlay;
/** Maps a widget name to its payload using a data source. */
final class OverlayService {
public const WIDGETS = array( 'goal', 'timer', 'counter', 'alerts' );
public const WIDGETS = array( 'goal', 'timer', 'counter', 'alerts', 'actions' );
public function __construct( private OverlayDataSource $source ) {}
@@ -38,10 +38,15 @@ final class OverlayService {
}
$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();
$actions = ( ( $recent || null !== $since ) && $ids && $this->source instanceof ActionsSource ) ? $this->source->actionsFor( $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();
}
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent );
case 'actions':
$rows = ( $gid && $this->source instanceof ActionsSource ) ? $this->source->menuActions( $gid ) : array();
return Payloads::actionsMenu( $goal, $rows );
}
return null;
}
+65
View File
@@ -126,6 +126,7 @@ final class Payloads {
'currency' => $cur,
'message' => (string) ( $r['message'] ?? '' ),
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
'actions' => self::actionEvents( $r['actions'] ?? array() ),
);
}
@@ -158,6 +159,70 @@ final class Payloads {
return $out;
}
/** Display-safe single line: no tags, control chars or runs of whitespace; capped at $max characters. */
public static function text( mixed $v, int $max ): string {
if ( ! is_scalar( $v ) ) {
return '';
}
$s = strip_tags( (string) $v );
$s = (string) preg_replace( '/[\x00-\x1F\x7F\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}\x{FEFF}]+/u', ' ', $s );
$s = trim( (string) preg_replace( '/\s+/u', ' ', $s ) );
return mb_substr( $s, 0, $max );
}
/**
* Triggered actions for one alert: [ {title, times} ]. At most 5, titles capped at 80 chars, times clamped to 1..999.
*
* @param mixed $events
* @return array<int,array{title:string,times:int}>
*/
public static function actionEvents( mixed $events ): array {
$out = array();
foreach ( is_array( $events ) ? $events : array() as $e ) {
if ( ! is_array( $e ) ) {
continue;
}
$title = self::text( $e['title'] ?? '', 80 );
if ( '' === $title ) {
continue;
}
$out[] = array( 'title' => $title, 'times' => max( 1, min( 999, (int) ( $e['times'] ?? 1 ) ) ) );
if ( count( $out ) >= 5 ) {
break;
}
}
return $out;
}
/**
* The on-stream reward menu for the active goal. Empty list means "render nothing".
*
* @param array<string,mixed>|null $goal
* @param array<int,array<string,mixed>> $rows Raw sg_actions rows, already ordered.
*/
public static function actionsMenu( ?array $goal, array $rows ): array {
$cur = strtoupper( (string) ( $goal['currency'] ?? 'USD' ) );
$list = array();
foreach ( $goal ? $rows : array() as $r ) {
$amount = (int) ( $r['amount_minor'] ?? 0 );
$title = self::text( $r['title'] ?? '', 120 );
if ( $amount <= 0 || '' === $title ) {
continue;
}
$list[] = array(
'title' => $title,
'description' => self::text( $r['description'] ?? '', 255 ),
'amount_minor' => $amount,
'amount_display' => self::money( $amount, $cur ),
'mode' => 'every' === ( $r['mode'] ?? '' ) ? 'every' : 'exact',
);
if ( count( $list ) >= 50 ) {
break;
}
}
return array( 'active' => (bool) $list, 'currency' => $cur, 'actions' => $list );
}
/** 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'] );
+2 -2
View File
@@ -8,7 +8,7 @@ use StreamGoals\Rest\OverlayController;
/** Serves the transparent OBS browser-source page at /streamgoals-overlay/{token}/{widget}/. */
final class Router {
public const RULES_VERSION = '1';
public const RULES_VERSION = '2';
private const OPTION = 'sg_overlay_rules_version';
public static function register(): void {
@@ -19,7 +19,7 @@ final class Router {
public static function add_rules(): void {
add_rewrite_rule(
'^streamgoals-overlay/([A-Za-z0-9]{16,128})/(goal|timer|counter|alerts)/?$',
'^streamgoals-overlay/([A-Za-z0-9]{16,128})/(goal|timer|counter|alerts|actions)/?$',
'index.php?sg_overlay_token=$matches[1]&sg_overlay_widget=$matches[2]',
'top'
);
+31 -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, RecentDonationsSource {
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource {
private function t( string $name ): string {
global $wpdb;
@@ -87,6 +87,36 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource {
return $out;
}
public function menuActions( int $goalId ): array {
global $wpdb;
$min = \StreamGoals\Core\Settings::effectiveMin( (int) \StreamGoals\Core\Settings::get( 'min_donation_minor', 0 ) );
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT title, description, amount_minor, mode FROM {$this->t('actions')}
WHERE enabled = 1 AND goal_id IN (0, %d) AND amount_minor >= %d ORDER BY sort, amount_minor, id LIMIT 50",
$goalId,
$min
), ARRAY_A );
return (array) $rows;
}
public function actionsFor( 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 donation_id, title, times FROM {$this->t('action_events')} WHERE donation_id IN ($in) ORDER BY id ASC",
$ids
), ARRAY_A );
$out = array();
foreach ( (array) $rows as $row ) {
$out[ (int) $row['donation_id'] ][] = array( 'title' => (string) $row['title'], 'times' => (int) $row['times'] );
}
return $out;
}
public function donations( ?int $sinceId, int $limit ): array {
global $wpdb;
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
+6
View File
@@ -87,6 +87,12 @@ final class DonationStore {
/** 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 );
// 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
}
}
private static function call_engine( string $method, int $id ): void {
+41 -1
View File
@@ -155,7 +155,8 @@ final class DonateController {
return '<p class="sg-donate-unavailable">' . esc_html__( 'Donations are not available right now.', 'streamgoals-donate' ) . '</p>';
}
$goals = array();
$goals = array();
$actions = self::actions_by_goal( array_map( static fn( $g ) => (int) $g['id'], DonationStore::active_goals() ), \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ) );
foreach ( DonationStore::active_goals() as $g ) {
if ( $pinned && (int) $g['id'] !== $pinned ) {
continue;
@@ -165,6 +166,7 @@ final class DonateController {
'title' => (string) $g['title'],
'currency' => strtoupper( (string) $g['currency'] ),
'exp' => Money::exponent( (string) $g['currency'] ),
'actions' => $actions[ (int) $g['id'] ] ?? array(),
);
}
if ( ! $goals ) {
@@ -196,6 +198,9 @@ final class DonateController {
'fixForm' => __( 'Please fix the form before paying.', 'streamgoals-donate' ),
'customAmount' => __( 'Or enter your own amount', 'streamgoals-donate' ),
'customPlaceholder' => __( 'Other amount', 'streamgoals-donate' ),
/* translators: %s: formatted amount, e.g. $5.00 */
'everyLabel' => __( 'Every %s', 'streamgoals-donate' ),
'actionsHint' => __( 'Pick a reward, or enter your own amount below.', 'streamgoals-donate' ),
/* translators: %s: formatted minimum amount, e.g. $1.00 */
'minHint' => __( 'Minimum donation: %s', 'streamgoals-donate' ),
/* translators: %s: formatted minimum amount, e.g. $1.00 */
@@ -211,6 +216,41 @@ final class DonateController {
/* ------------------------------------------------------------- Helpers */
/**
* Enabled actions per goal id (rows with goal_id 0 apply to every goal), at or above the effective minimum.
* Public-safe fields only. One query; reads sg_actions directly.
*
* @param int[] $goalIds
* @return array<int,array<int,array<string,mixed>>>
*/
private static function actions_by_goal( array $goalIds, int $min ): array {
global $wpdb;
$out = array();
if ( ! $goalIds ) {
return $out;
}
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT id, goal_id, title, description, amount_minor, mode FROM {$wpdb->prefix}sg_actions
WHERE enabled = 1 AND amount_minor >= %d ORDER BY sort, amount_minor, id LIMIT 500",
max( 1, $min )
), ARRAY_A );
foreach ( (array) $rows as $r ) {
$item = array(
'id' => (int) $r['id'],
'title' => (string) $r['title'],
'description' => (string) $r['description'],
'amount_minor' => (int) $r['amount_minor'],
'mode' => 'every' === $r['mode'] ? 'every' : 'exact',
);
foreach ( $goalIds as $gid ) {
if ( 0 === (int) $r['goal_id'] || (int) $r['goal_id'] === $gid ) {
$out[ $gid ][] = $item;
}
}
}
return $out;
}
/** Only whitelisted client fields are read; totals/fees from the client are ignored. */
private static function input( \WP_REST_Request $req ): array {
$out = array();
+1 -1
View File
@@ -18,7 +18,7 @@ final class OverlayController {
}
public static function routes(): void {
register_rest_route( 'streamgoals/v1', '/overlay/(?P<token>[A-Za-z0-9]{16,128})/(?P<widget>goal|timer|counter|alerts)', array(
register_rest_route( 'streamgoals/v1', '/overlay/(?P<token>[A-Za-z0-9]{16,128})/(?P<widget>goal|timer|counter|alerts|actions)', array(
'methods' => 'GET',
'callback' => array( self::class, 'handle' ),
'permission_callback' => '__return_true', // capability is the unguessable token, checked in handle()
+67
View File
@@ -0,0 +1,67 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Admin\ActionInput;
final class ActionInputTest extends TestCase {
private function post( array $o = array() ): array {
return $o + array( 'title' => 'Eat a bean', 'description' => '', 'amount' => '5.00', 'mode' => 'every', 'goal_id' => '0', 'sort' => '' );
}
private function v( array $o = array(), int $min = 100 ): array {
return ActionInput::validate( $this->post( $o ), $min, 'USD', array( 3, 4 ), 40 );
}
public function test_valid_input(): void {
$r = $this->v( array( 'title' => ' <b>Eat</b> a bean ', 'description' => 'Yum', 'goal_id' => '3' ) );
$this->assertNull( $r['error'] );
$this->assertSame( array( 'goal_id' => 3, 'title' => 'Eat a bean', 'description' => 'Yum', 'amount_minor' => 500, 'mode' => 'every', 'sort' => 40 ), $r['data'] );
}
public function test_title_required_and_max_120(): void {
$this->assertNull( $this->v( array( 'title' => ' ' ) )['data'] );
$this->assertNull( $this->v( array( 'title' => str_repeat( 'a', 121 ) ) )['data'] );
$this->assertNotNull( $this->v( array( 'title' => str_repeat( 'a', 120 ) ) )['data'] );
}
public function test_description_max_255(): void {
$this->assertNull( $this->v( array( 'description' => str_repeat( 'a', 256 ) ) )['data'] );
$this->assertNotNull( $this->v( array( 'description' => str_repeat( 'a', 255 ) ) )['data'] );
}
public function test_amount_must_reach_the_minimum(): void {
$low = $this->v( array( 'amount' => '0.99' ) );
$this->assertNull( $low['data'] );
$this->assertStringContainsString( 'minimum', (string) $low['error'] );
$this->assertNotNull( $this->v( array( 'amount' => '1.00' ) )['data'] );
$this->assertNull( $this->v( array( 'amount' => '4.99' ), 500 )['data'] );
$this->assertNotNull( $this->v( array( 'amount' => '5' ), 500 )['data'] );
}
public function test_bad_amounts(): void {
foreach ( array( '', '0', '-5', 'abc', '5.123' ) as $bad ) {
$this->assertNull( $this->v( array( 'amount' => $bad ) )['data'], "amount '$bad'" );
}
}
public function test_mode_whitelist(): void {
$this->assertNotNull( $this->v( array( 'mode' => 'exact' ) )['data'] );
$this->assertNull( $this->v( array( 'mode' => 'always' ) )['data'] );
$this->assertNull( $this->v( array( 'mode' => null ) )['data'] );
}
public function test_goal_must_exist_or_be_zero(): void {
$this->assertNotNull( $this->v( array( 'goal_id' => '4' ) )['data'] );
$this->assertNull( $this->v( array( 'goal_id' => '99' ) )['data'] );
$this->assertNull( $this->v( array( 'goal_id' => '-1' ) )['data'] );
}
public function test_sort(): void {
$this->assertSame( 7, $this->v( array( 'sort' => '7' ) )['data']['sort'] );
$this->assertNull( $this->v( array( 'sort' => 'x' ) )['data'] );
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Actions\Matcher;
final class ActionMatcherTest extends TestCase {
private function a( int $id, int $amount, string $mode, string $title = '' ): array {
return array( 'id' => $id, 'title' => '' === $title ? "A$id" : $title, 'amount_minor' => $amount, 'mode' => $mode );
}
public function test_exact_matches_only_the_same_amount(): void {
$acts = array( $this->a( 1, 2500, 'exact' ) );
$this->assertSame( array( array( 'action_id' => 1, 'title' => 'A1', 'times' => 1 ) ), Matcher::match( 2500, $acts ) );
$this->assertSame( array(), Matcher::match( 2501, $acts ) );
$this->assertSame( array(), Matcher::match( 5000, $acts ) );
}
public function test_every_uses_floor_of_multiples(): void {
$acts = array( $this->a( 1, 500, 'every' ) );
$this->assertSame( 5, Matcher::match( 2500, $acts )[0]['times'] );
$this->assertSame( 2, Matcher::match( 1099, $acts )[0]['times'], 'floor, not round' );
$this->assertSame( 1, Matcher::match( 500, $acts )[0]['times'] );
}
public function test_below_amount_never_matches(): void {
$this->assertSame( array(), Matcher::match( 499, array( $this->a( 1, 500, 'every' ), $this->a( 2, 500, 'exact' ) ) ) );
}
public function test_zero_and_negative_donations_match_nothing(): void {
$acts = array( $this->a( 1, 100, 'every' ) );
$this->assertSame( array(), Matcher::match( 0, $acts ) );
$this->assertSame( array(), Matcher::match( -500, $acts ) );
}
public function test_zero_and_negative_action_amounts_never_match(): void {
$this->assertSame( array(), Matcher::match( 500, array( $this->a( 1, 0, 'every' ), $this->a( 2, -5, 'exact' ), $this->a( 3, -500, 'every' ) ) ) );
}
public function test_several_actions_at_once_in_input_order(): void {
$acts = array( $this->a( 7, 2500, 'exact', '25 pushups' ), $this->a( 3, 500, 'every', 'Eat a bean' ), $this->a( 9, 1000, 'exact' ) );
$this->assertSame(
array(
array( 'action_id' => 7, 'title' => '25 pushups', 'times' => 1 ),
array( 'action_id' => 3, 'title' => 'Eat a bean', 'times' => 5 ),
),
Matcher::match( 2500, $acts )
);
}
public function test_ordering_is_stable_not_resorted(): void {
$acts = array( $this->a( 5, 100, 'every' ), $this->a( 2, 100, 'every' ), $this->a( 9, 100, 'every' ) );
$this->assertSame( array( 5, 2, 9 ), array_column( Matcher::match( 300, $acts ), 'action_id' ) );
}
public function test_bad_rows_are_ignored(): void {
$acts = array(
'junk',
null,
array(),
array( 'id' => 1, 'title' => 'x', 'amount_minor' => 100 ),
array( 'id' => 2, 'title' => 'x', 'amount_minor' => 100, 'mode' => 'weird' ),
array( 'id' => 0, 'title' => 'x', 'amount_minor' => 100, 'mode' => 'every' ),
array( 'id' => 'abc', 'title' => 'x', 'amount_minor' => 100, 'mode' => 'every' ),
array( 'id' => 3, 'title' => 'x', 'amount_minor' => 'lots', 'mode' => 'every' ),
array( 'id' => 4, 'title' => array(), 'amount_minor' => 100, 'mode' => 'every' ),
array( 'id' => '5', 'title' => 'Good', 'amount_minor' => '100', 'mode' => 'every' ),
);
$this->assertSame( array( array( 'action_id' => 5, 'title' => 'Good', 'times' => 2 ) ), Matcher::match( 200, $acts ) );
}
public function test_empty_menu(): void {
$this->assertSame( array(), Matcher::match( 1000, array() ) );
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Actions\ActionRepository;
final class ActionRepositoryTest extends TestCase {
private function fake(): object {
if ( ! defined( 'ARRAY_A' ) ) {
define( 'ARRAY_A', 'ARRAY_A' );
}
return new class() {
public string $prefix = 'wp_';
public array $sql = array();
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 ) { $this->sql[] = $q; return 1; }
public function get_results( string $q, $o = null ): array { $this->sql[] = $q; return $this->rows; }
};
}
public function test_record_events_is_insert_ignore(): void {
$db = $this->fake();
( new ActionRepository( $db ) )->recordEvents( 10, array( array( 'action_id' => 2, 'title' => 'Eat', 'times' => 5 ), array( 'action_id' => 3, 'title' => 'Push', 'times' => 1 ) ) );
$this->assertCount( 2, $db->sql );
foreach ( $db->sql as $q ) {
$this->assertStringStartsWith( 'INSERT IGNORE INTO wp_sg_action_events', $q );
}
$this->assertStringContainsString( "VALUES (10, 2, 5, 'Eat', 'queued'", $db->sql[0] );
}
public function test_record_events_skips_invalid_matches(): void {
$db = $this->fake();
$repo = new ActionRepository( $db );
$repo->recordEvents( 10, array( array( 'action_id' => 0, 'title' => 'x', 'times' => 1 ), array( 'action_id' => 2, 'title' => 'x', 'times' => 0 ) ) );
$repo->recordEvents( 0, array( array( 'action_id' => 2, 'title' => 'x', 'times' => 1 ) ) );
$this->assertSame( array(), $db->sql );
}
public function test_enabled_for_goal_filter_and_row_shape(): void {
$db = $this->fake();
$db->rows = array( array( 'id' => '4', 'goal_id' => '0', 'title' => 'T', 'description' => 'D', 'amount_minor' => '500', 'mode' => 'every', 'enabled' => '1', 'sort' => '10', 'created_at' => '2026-01-01 00:00:00' ) );
$rows = ( new ActionRepository( $db ) )->enabledForGoal( 7 );
$q = $db->sql[0];
$this->assertStringContainsString( 'enabled = 1', $q );
$this->assertStringContainsString( 'goal_id IN (0, 7)', $q );
$this->assertStringContainsString( 'ORDER BY sort ASC, amount_minor ASC', $q );
$this->assertSame( 4, $rows[0]['id'] );
$this->assertSame( 500, $rows[0]['amount_minor'] );
$this->assertSame( array( 'id', 'goal_id', 'title', 'description', 'amount_minor', 'mode', 'enabled', 'sort', 'created_at' ), array_keys( $rows[0] ) );
}
public function test_mark_done_only_touches_queued_rows(): void {
$db = $this->fake();
$this->assertTrue( ( new ActionRepository( $db ) )->markDone( 5 ) );
$this->assertStringContainsString( "AND status = 'queued'", $db->sql[0] );
}
public function test_installer_schema_defines_both_tables_and_unique_key(): void {
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
$this->assertStringContainsString( "DB_VERSION = '2'", $src );
$this->assertStringContainsString( 'CREATE TABLE {$p}actions (', $src );
$this->assertStringContainsString( 'CREATE TABLE {$p}action_events (', $src );
$this->assertStringContainsString( 'UNIQUE KEY donation_action (donation_id,action_id)', $src );
}
}
+124
View File
@@ -0,0 +1,124 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Overlay\ActionsSource;
use StreamGoals\Overlay\OverlayDataSource;
use StreamGoals\Overlay\OverlayService;
use StreamGoals\Overlay\Payloads;
use StreamGoals\Overlay\RecentDonationsSource;
final class OverlayActionsTest extends TestCase {
/** @param array<int,array> $menu @param array<int,array> $events @param array<int,array> $db */
private function svc( array $menu, array $events, array $db, bool $goal = true ): OverlayService {
return new OverlayService( new class( $menu, $events, $db, $goal ) implements OverlayDataSource, RecentDonationsSource, ActionsSource {
public int $actionQueries = 0;
public function __construct( private array $menu, private array $events, private array $db, private bool $goal ) {}
public function activeGoal(): ?array { return $this->goal ? array( 'id' => 7, 'currency' => 'USD' ) : 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(); }
public function donations( ?int $sinceId, int $limit ): array {
return array_values( array_filter( $this->db, static fn( $d ) => $d['id'] > (int) $sinceId ) );
}
public function recentDonations( int $limit ): array { return $this->db; }
public function menuActions( int $goalId ): array { return $this->menu; }
public function actionsFor( array $ids ): array { ++$this->actionQueries; return $this->events; }
} );
}
private function row( int $id, array $o = array() ): array {
return $o + array( 'id' => $id, 'base_minor' => 2500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0,
'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
}
public function test_menu_lists_actions_with_display_and_mode(): void {
$menu = array(
array( 'title' => 'Eat a bean', 'description' => 'every flavor', 'amount_minor' => 500, 'mode' => 'every' ),
array( 'title' => '25 pushups', 'description' => '', 'amount_minor' => 2500, 'mode' => 'exact' ),
);
$out = $this->svc( $menu, array(), array() )->payload( 'actions', 1 );
$this->assertTrue( $out['active'] );
$this->assertSame( '$5.00', $out['actions'][0]['amount_display'] );
$this->assertSame( 'every', $out['actions'][0]['mode'] );
$this->assertSame( 'exact', $out['actions'][1]['mode'] );
$this->assertSame( '25 pushups', $out['actions'][1]['title'] );
}
public function test_menu_empty_without_goal_or_actions_and_drops_bad_rows(): void {
$this->assertFalse( $this->svc( array(), array(), array() )->payload( 'actions', 1 )['active'] );
$menu = array( array( 'title' => 'x', 'amount_minor' => 500, 'mode' => 'exact' ) );
$this->assertSame( array(), $this->svc( $menu, array(), array(), false )->payload( 'actions', 1 )['actions'] );
$bad = array( array( 'title' => 'Zero', 'amount_minor' => 0 ), array( 'title' => ' ', 'amount_minor' => 500 ) );
$this->assertSame( array(), Payloads::actionsMenu( array( 'currency' => 'USD' ), $bad )['actions'] );
}
public function test_menu_sanitizes_hostile_strings(): void {
$menu = array( array( 'title' => "<script>alert(1)</script>Do\x00 it\n now", 'description' => '<img src=x onerror=1>' . str_repeat( 'd', 400 ), 'amount_minor' => 500, 'mode' => 'weird' ) );
$a = Payloads::actionsMenu( array( 'currency' => 'USD' ), $menu )['actions'][0];
$this->assertStringNotContainsString( '<', $a['title'] . $a['description'] );
$this->assertStringNotContainsString( "\n", $a['title'] );
$this->assertLessThanOrEqual( 255, mb_strlen( $a['description'] ) );
$this->assertSame( 'exact', $a['mode'] );
}
public function test_alert_actions_shown_with_times_in_since_and_recent(): void {
$events = array( 3 => array( array( 'title' => 'Eat a bean', 'times' => 3 ), array( 'title' => '25 pushups', 'times' => 1 ) ) );
$db = array( $this->row( 3, array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ), $this->row( 4 ) );
$svc = $this->svc( array(), $events, $db );
$since = $svc->payload( 'alerts', 1, 0 );
$recent = $svc->payload( 'alerts', 1, null, true );
$this->assertSame( $since['alerts'], $recent['alerts'] );
$a = $recent['alerts'][0];
$this->assertSame( array( array( 'title' => 'Eat a bean', 'times' => 3 ), array( 'title' => '25 pushups', 'times' => 1 ) ), $a['actions'] );
$this->assertSame( 'Anonymous', $a['name'] );
$this->assertStringNotContainsString( 'Secret', json_encode( $recent ) );
$this->assertSame( array(), $recent['alerts'][1]['actions'] );
}
public function test_alert_actions_use_one_query_and_baseline_none(): void {
$db = array( $this->row( 3 ), $this->row( 4 ) );
$svc = $this->svc( array(), array(), $db );
$svc->payload( 'alerts', 1, null, true );
$this->assertSame( array(), $svc->payload( 'alerts', 1, null )['alerts'] );
}
public function test_alert_actions_sanitized_capped_and_clamped(): void {
$ev = array( array( 'title' => '<b>Hi</b>', 'times' => 0 ), array( 'title' => '', 'times' => 2 ), 'junk', array( 'title' => str_repeat( 'é', 200 ), 'times' => 99999 ) );
for ( $i = 0; $i < 10; $i++ ) {
$ev[] = array( 'title' => "T$i", 'times' => 1 );
}
$out = Payloads::actionEvents( $ev );
$this->assertCount( 5, $out );
$this->assertSame( array( 'title' => 'Hi', 'times' => 1 ), $out[0] );
$this->assertSame( 80, mb_strlen( $out[1]['title'] ) );
$this->assertSame( 999, $out[1]['times'] );
$this->assertSame( array(), Payloads::actionEvents( 'nope' ) );
}
public function test_etag_changes_when_actions_appear(): void {
$db = array( $this->row( 3 ) );
$none = $this->svc( array(), array(), $db )->payload( 'alerts', 1, null, true );
$with = $this->svc( array(), array( 3 => array( array( 'title' => 'Bean', 'times' => 1 ) ) ), $db )->payload( 'alerts', 1, null, true );
$this->assertNotSame( Payloads::etag( $none ), Payloads::etag( $with ) );
$m1 = $this->svc( array(), array(), array() )->payload( 'actions', 1 );
$m2 = $this->svc( array( array( 'title' => 'Bean', 'amount_minor' => 500, 'mode' => 'exact' ) ), array(), array() )->payload( 'actions', 1 );
$this->assertNotSame( Payloads::etag( $m1 ), Payloads::etag( $m2 ) );
}
public function test_source_without_actions_capability_still_works(): void {
$svc = new OverlayService( new class implements OverlayDataSource {
public function activeGoal(): ?array { return array( 'id' => 1, '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 array(); }
public function bonusesFor( array $ids ): array { return array(); }
} );
$this->assertFalse( $svc->payload( 'actions', 1 )['active'] );
}
}