Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 b0b5012698 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>
2026-11-15 12:36:28 -08:00
shadowdaoandClaude Sonnet 5.5 c62ac06b27 docs: donation actions contract
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:33:50 -08:00
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
35 changed files with 1666 additions and 30 deletions

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));
+17 -1
View File
@@ -27,7 +27,23 @@ 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)}}
.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}}
+72 -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,19 @@
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]) + '!'));
}
}
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 () {
@@ -116,10 +145,48 @@
}, 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;
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() {
@@ -156,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();
+19
View File
@@ -54,3 +54,22 @@ A toggle on the donate form (default **off**). Form shows exact total before pay
## Defaults
Currency USD (configurable per goal). Sandbox mode is the default until the owner switches to Live.
## Donation actions ("rewards") — contract
Streamers attach on-stream actions to dollar amounts (e.g. $5 = "Eat an every-flavor bean", $25 = "25 pushups").
Tables (Installer, DB_VERSION 2):
- `sg_actions`: id, goal_id (0 = applies to every goal), title VARCHAR(120), description VARCHAR(255), amount_minor BIGINT UNSIGNED,
mode VARCHAR(8) `exact` (donation base amount == amount) | `every` (each whole multiple of amount: times = floor(base/amount)),
enabled TINYINT, sort INT, created_at.
- `sg_action_events`: id, donation_id, action_id, times INT, title VARCHAR(120) (snapshot at trigger time), status `queued`|`done`,
created_at, done_at NULL. UNIQUE(donation_id, action_id) so a replayed capture/webhook never double-queues.
PHP (namespace `StreamGoals\Actions`):
- `Matcher::match(int $baseMinor, array $actions): array` — PURE. `$actions` = rows with keys id, title, amount_minor, mode.
Returns `[ ['action_id'=>int,'title'=>string,'times'=>int], ... ]`; a donation may trigger several actions (e.g. $25 matches "every $5" x5 and exact "$25"). amount_minor <= 0 never matches.
- `ActionRepository` ($wpdb): `enabledForGoal(int $goalId): array` (enabled rows where goal_id IN (0,$goalId), ORDER BY sort, amount_minor), CRUD for admin,
`recordEvents(int $donationId, array $matches): void` (INSERT IGNORE, idempotent), `queued(int $limit): array`, `markDone(int $eventId): bool`.
- `Recorder::forDonation(int $donationId): void` — called after a donation becomes `completed` (same place the rules engine is applied); matches on the donation's BASE amount (not fee cover) using the goal's enabled actions and records events. Never throws.
Public/overlay: the donate form shows each enabled action as a button (amount + title); the overlay has a new `actions` widget (the menu for the active goal) and alert payloads gain `actions`: `[ {title, times} ]` read from sg_action_events (anonymous donors' actions are still shown; names stay masked).
Amounts must be >= Settings::effectiveMin().
+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} */
+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
+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;
}
+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;
}
+23 -3
View File
@@ -6,11 +6,11 @@ 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 ) {}
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,27 @@ 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();
$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;
}
+120 -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,116 @@ 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() ),
'actions' => self::actionEvents( $r['actions'] ?? 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;
}
/** 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'] );
@@ -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;
}
+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'
);
+66 -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, ActionsSource {
private function t( string $name ): string {
global $wpdb;
@@ -62,6 +62,61 @@ 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 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';
@@ -77,4 +132,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 );
}
}
+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();
+4 -2
View File
@@ -18,12 +18,13 @@ 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()
'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 );
}
/**
+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 );
}
}
+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' );
}
}
+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'] );
}
}
+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 ) ) );
}
}