diff --git a/assets/admin/actions.js b/assets/admin/actions.js new file mode 100644 index 0000000..c4f7764 --- /dev/null +++ b/assets/admin/actions.js @@ -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(); +}() ); diff --git a/assets/donate/donate.css b/assets/donate/donate.css index 2dfe6d8..594f990 100644 --- a/assets/donate/donate.css +++ b/assets/donate/donate.css @@ -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} diff --git a/assets/donate/donate.js b/assets/donate/donate.js index abed65f..95536e9 100644 --- a/assets/donate/donate.js +++ b/assets/donate/donate.js @@ -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)); diff --git a/assets/overlay/overlay.css b/assets/overlay/overlay.css index fbc82bd..f96c25b 100644 --- a/assets/overlay/overlay.css +++ b/assets/overlay/overlay.css @@ -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}} diff --git a/assets/overlay/overlay.js b/assets/overlay/overlay.js index 87054db..72c93e4 100644 --- a/assets/overlay/overlay.js +++ b/assets/overlay/overlay.js @@ -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(); diff --git a/includes/Actions/ActionRepository.php b/includes/Actions/ActionRepository.php new file mode 100644 index 0000000..7b5d1f1 --- /dev/null +++ b/includes/Actions/ActionRepository.php @@ -0,0 +1,155 @@ +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' ) ) ); + } +} diff --git a/includes/Actions/Matcher.php b/includes/Actions/Matcher.php new file mode 100644 index 0000000..3539508 --- /dev/null +++ b/includes/Actions/Matcher.php @@ -0,0 +1,46 @@ + 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; + } +} diff --git a/includes/Actions/Recorder.php b/includes/Actions/Recorder.php new file mode 100644 index 0000000..fd3e2cd --- /dev/null +++ b/includes/Actions/Recorder.php @@ -0,0 +1,26 @@ +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 + } + } +} diff --git a/includes/Admin/ActionInput.php b/includes/Admin/ActionInput.php new file mode 100644 index 0000000..21bd3f6 --- /dev/null +++ b/includes/Admin/ActionInput.php @@ -0,0 +1,58 @@ + 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 ); + } +} diff --git a/includes/Admin/ActionsPage.php b/includes/Admin/ActionsPage.php new file mode 100644 index 0000000..8a55079 --- /dev/null +++ b/includes/Admin/ActionsPage.php @@ -0,0 +1,219 @@ +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 '

Waiting to be done (' . count( $queued ) . ')

'; + if ( ! $queued ) { + echo '

Nothing in the queue. When a donation triggers a reward, it shows up here.

'; + } else { + echo ''; + foreach ( $queued as $e ) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
DonorAmountRewardTimeMessage
' . esc_html( Format::donorName( $e ) ) . '' . esc_html( Format::money( (int) ( $e['base_minor'] ?? 0 ), Format::currency( $e['currency'] ?? $cur ) ) ) . '' . esc_html( (string) $e['title'] ) . ' × ' . (int) $e['times'] . '' . esc_html( self::when( (string) $e['created_at'] ) ) . '' . esc_html( (string) ( $e['message'] ?? '' ) ) . ''; + Admin::form( 'sg_event_done', array( 'event_id' => (int) $e['id'] ), 'sg-inline' ); + echo '
'; + Admin::form( 'sg_event_done_all' ); + echo '

'; + } + $done = $repo->recentDone( 15 ); + if ( $done ) { + echo '

Recently done

'; + } + echo '
'; + } + + private static function when( string $utc ): string { + return '' === $utc ? '' : get_date_from_gmt( $utc, 'Y-m-d H:i' ); + } + + /** @return array 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 '

Your reward menu

'; + echo '

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.

'; + echo '

Add a reward

'; + if ( ! $actions ) { + echo '

No rewards yet.

'; + return; + } + echo ''; + foreach ( $actions as $a ) { + $id = (int) $a['id']; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
RewardAmountTriggersApplies toOrderActions
' . esc_html( $a['title'] ) . ''; + if ( '' !== $a['description'] ) { + echo '
' . esc_html( $a['description'] ) . ''; + } + echo '
' . esc_html( Format::money( $a['amount_minor'], $cur ) ) . '' . esc_html( Matcher::EVERY === $a['mode'] ? 'Every time it adds up' : 'Exactly this amount' ) . '' . esc_html( 0 === $a['goal_id'] ? 'All goals' : ( $goals[ $a['goal_id'] ] ?? 'Goal #' . $a['goal_id'] ) ) . '' . (int) $a['sort'] . ''; + echo 'Edit '; + Admin::form( 'sg_action_toggle', array( 'action_id' => $id, 'enabled' => $a['enabled'] ? 0 : 1 ), 'sg-inline' ); + echo ' '; + Admin::form( 'sg_action_delete', array( 'action_id' => $id ), 'sg-inline sg-confirm' ); + echo ''; + echo '
'; + } + + private static function renderForm( int $id ): void { + $a = $id ? self::repo()->find( $id ) : null; + if ( $id && ! $a ) { + echo '

That reward no longer exists. Back to rewards

'; + 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 '

' . ( $a ? 'Edit reward' : 'Add a reward' ) . '

'; + Admin::form( 'sg_action_save', array( 'action_id' => $id ), 'sg-action-form' ); + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo '

What would a donation do?

'; + echo '

'; + echo '
'; + echo '

Cancel

'; + } + + /* -------------------------------------------------------------- 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.' ); + } +} diff --git a/includes/Admin/Admin.php b/includes/Admin/Admin.php index 4ed953c..c70584f 100644 --- a/includes/Admin/Admin.php +++ b/includes/Admin/Admin.php @@ -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 ? ' ' . (int) $pending . '' : ''; add_submenu_page( self::HOME, 'Moderation', 'Moderation' . $badge, self::CAP, 'streamgoals-moderation', array( DonationsPage::class, 'renderModeration' ) ); } + $queued = ActionsPage::queuedCount(); + $qbadge = $queued > 0 ? ' ' . (int) $queued . '' : ''; + 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 ); } diff --git a/includes/Admin/OverlaysPage.php b/includes/Admin/OverlaysPage.php index fac3624..aa3d54f 100644 --- a/includes/Admin/OverlaysPage.php +++ b/includes/Admin/OverlaysPage.php @@ -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} */ diff --git a/includes/Core/Installer.php b/includes/Core/Installer.php index c8e4d8f..bc95885 100644 --- a/includes/Core/Installer.php +++ b/includes/Core/Installer.php @@ -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 ); } } diff --git a/includes/Overlay/ActionsSource.php b/includes/Overlay/ActionsSource.php new file mode 100644 index 0000000..c9e0d8f --- /dev/null +++ b/includes/Overlay/ActionsSource.php @@ -0,0 +1,25 @@ +> + */ + 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>> donation id => events + */ + public function actionsFor( array $donationIds ): array; +} diff --git a/includes/Overlay/OverlayService.php b/includes/Overlay/OverlayService.php index 2558c11..eb94ea2 100644 --- a/includes/Overlay/OverlayService.php +++ b/includes/Overlay/OverlayService.php @@ -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; } diff --git a/includes/Overlay/Payloads.php b/includes/Overlay/Payloads.php index c65b25b..5754750 100644 --- a/includes/Overlay/Payloads.php +++ b/includes/Overlay/Payloads.php @@ -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 + */ + 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|null $goal + * @param array> $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'] ); diff --git a/includes/Overlay/Router.php b/includes/Overlay/Router.php index 3da68c6..8a7d7e2 100644 --- a/includes/Overlay/Router.php +++ b/includes/Overlay/Router.php @@ -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' ); diff --git a/includes/Overlay/WpdbDataSource.php b/includes/Overlay/WpdbDataSource.php index 9b1bca2..1ddd2ec 100644 --- a/includes/Overlay/WpdbDataSource.php +++ b/includes/Overlay/WpdbDataSource.php @@ -4,7 +4,7 @@ declare( strict_types=1 ); namespace StreamGoals\Overlay; /** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */ -final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource { +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'; diff --git a/includes/PayPal/DonationStore.php b/includes/PayPal/DonationStore.php index b250d59..68f2299 100644 --- a/includes/PayPal/DonationStore.php +++ b/includes/PayPal/DonationStore.php @@ -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 { diff --git a/includes/Rest/DonateController.php b/includes/Rest/DonateController.php index 54039ce..c714035 100644 --- a/includes/Rest/DonateController.php +++ b/includes/Rest/DonateController.php @@ -155,7 +155,8 @@ final class DonateController { return '

' . esc_html__( 'Donations are not available right now.', 'streamgoals-donate' ) . '

'; } - $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>> + */ + 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(); diff --git a/includes/Rest/OverlayController.php b/includes/Rest/OverlayController.php index 055a681..b8c5101 100644 --- a/includes/Rest/OverlayController.php +++ b/includes/Rest/OverlayController.php @@ -18,7 +18,7 @@ final class OverlayController { } public static function routes(): void { - register_rest_route( 'streamgoals/v1', '/overlay/(?P[A-Za-z0-9]{16,128})/(?Pgoal|timer|counter|alerts)', array( + register_rest_route( 'streamgoals/v1', '/overlay/(?P[A-Za-z0-9]{16,128})/(?Pgoal|timer|counter|alerts|actions)', array( 'methods' => 'GET', 'callback' => array( self::class, 'handle' ), 'permission_callback' => '__return_true', // capability is the unguessable token, checked in handle() diff --git a/tests/Unit/ActionInputTest.php b/tests/Unit/ActionInputTest.php new file mode 100644 index 0000000..75f26c6 --- /dev/null +++ b/tests/Unit/ActionInputTest.php @@ -0,0 +1,67 @@ + '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' => ' Eat 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'] ); + } +} diff --git a/tests/Unit/ActionMatcherTest.php b/tests/Unit/ActionMatcherTest.php new file mode 100644 index 0000000..1442b43 --- /dev/null +++ b/tests/Unit/ActionMatcherTest.php @@ -0,0 +1,78 @@ + $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() ) ); + } +} diff --git a/tests/Unit/ActionRepositoryTest.php b/tests/Unit/ActionRepositoryTest.php new file mode 100644 index 0000000..3b9e316 --- /dev/null +++ b/tests/Unit/ActionRepositoryTest.php @@ -0,0 +1,75 @@ +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 ); + } +} diff --git a/tests/Unit/OverlayActionsTest.php b/tests/Unit/OverlayActionsTest.php new file mode 100644 index 0000000..d73f84b --- /dev/null +++ b/tests/Unit/OverlayActionsTest.php @@ -0,0 +1,124 @@ + $menu @param array $events @param 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' => "Do\x00 it\n now", 'description' => '' . 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' => 'Hi', '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'] ); + } +}